Advertisement
krakaen

Quarry Turtle

Mar 1st, 2015
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 64.29 KB | None | 0 0
  1. -- ********************************************************************************** --
  2. -- **                                                                              ** --
  3. -- **   Minecraft Mining Turtle Ore Quarry v0.71 by AustinKK                       ** --
  4. -- **   ----------------------------------------------------                       ** --
  5. -- **                                                                              ** --
  6. -- **   For instructions on how to use:                                            ** --
  7. -- **                                                                              ** --
  8. -- **     http://www.youtube.com/watch?v=PIugLVzUz3g                               ** --
  9. -- **                                                                              ** --
  10. -- **  Change Log:                                                                 ** --
  11. -- **    27th Dec 2012: [v0.2] Initial Draft Release                               ** --
  12. -- **    29th Dec 2012: [v0.3] Minor Performance Improvements                      ** --
  13. -- **    30th Dec 2012: [v0.4] Further Performance Improvements                    ** --
  14. -- **    9th  Jan 2013: [v0.5] Debug Version (dropping off chest)                  ** --
  15. -- **    10th Jan 2013: [v0.51] Further Debug (dropping off chest)                 ** --
  16. -- **    10th Jan 2013: [v0.52] Fix for dropping off chest bug                     ** --
  17. -- **    11th Jan 2013: [v0.53] Fix for dropping off chest bug (release)           ** --
  18. -- **    12th Jan 2013: [v0.6] Added support for resume                            ** --
  19. -- **    31st Mar 2013: [v0.7] Fixes for ComputerCraft 1.52                        ** --
  20. -- **    25th Aug 2013: [v0.71] Support ComputerCraft 1.56 and Chunk Loader Module ** --
  21. -- **                                                                              ** --
  22. -- ********************************************************************************** --
  23.  
  24.  
  25. -- ********************************************************************************** --
  26. -- Note: If you are in a world with flat bedrock, change the value below from 5 to 2.
  27. --       You don't need to change this, but the turtle is slightly faster if you do.
  28. -- ********************************************************************************** --
  29. local bottomLayer = 7 -- The y co-ords of the layer immediately above bedrock
  30.  
  31.  
  32.  
  33. -- Enumeration to store the the different types of message that can be written
  34. messageLevel = { DEBUG=0, INFO=1, WARNING=2, ERROR=3, FATAL=4 }
  35.  
  36. -- Enumeration to store names for the 6 directions
  37. direction = { FORWARD=0, RIGHT=1, BACK=2, LEFT=3, UP=4, DOWN=5 }
  38.  
  39. -- Enumeration of mining states
  40. miningState = { START=0, LAYER=1, EMPTYCHESTDOWN=2, EMPTYINVENTORY=3 }
  41.  
  42. local messageOutputLevel = messageLevel.INFO
  43. local messageOutputFileName
  44. local fuelLevelToRefuelAt = 5
  45. local refuelItemsToUseWhenRefuelling = 63
  46. local emergencyFuelToRetain = 0
  47. local maximumGravelStackSupported = 25 -- The number of stacked gravel or sand blocks supported
  48. local noiseBlocksCount
  49. local returningToStart = false
  50. local lookForChests = false -- Determines if chests should be located as part of the quarrying
  51. local miningOffset -- The offset to the mining layer. This is set depending on whether chests are being looked for or not
  52. local lastEmptySlot -- The last inventory slot that was empty when the program started (is either 15 if not looking for chests or 14 if we are)
  53. local turtleId
  54. local isWirelessTurtle
  55. local currentlySelectedSlot = 0 -- The slot that the last noise block was found in
  56. local lastMoveNeededDig = true -- Determines whether the last move needed a dig first
  57. local haveBeenAtZeroZeroOnLayer -- Determines whether the turtle has been at (0, 0) in this mining layer
  58. local orientationAtZeroZero -- The turtle's orientation when it was at (0, 0)
  59. local levelToReturnTo -- The level that the turtle should return to in order to head back to the start to unload
  60.  
  61. -- Variables used to support a resume
  62. local startupParamsFile = "OreQuarryParams.txt"
  63. local oreQuarryLocation = "OreQuarryLocation.txt"
  64. local returnToStartFile = "OreQuarryReturn.txt"
  65. local startupBackup = "startup_bak"
  66. local supportResume = true -- Determines whether the turtle is being run in the mode that supports resume
  67. local resuming = false -- Determines whether the turtle is currently in the process of resuming
  68. local resumeX
  69. local resumeY
  70. local resumeZ
  71. local resumeOrient
  72. local resumeMiningState
  73.  
  74. -- Variables to store the current location and orientation of the turtle. x is right, left, y is up, down and
  75. -- z is forward, back with relation to the starting orientation. Y is the actual turtle level, x and z are
  76. -- in relation to the starting point (i.e. the starting point is (0, 0))
  77. local currX
  78. local currY
  79. local currZ
  80. local currOrient
  81. local currMiningState = miningState.START
  82.  
  83. -- Command line parameters
  84. local startHeight -- Represents the height (y co-ord) that the turtle started at
  85. local quarryWidth -- Represents the length of the mines that the turtle will dig
  86.  
  87. -- ********************************************************************************** --
  88. -- Writes an output message
  89. -- ********************************************************************************** --
  90. function writeMessage(message, msgLevel)
  91.   if (msgLevel >= messageOutputLevel) then
  92.     print(message)
  93.  
  94.     -- If this turtle has a modem, then write the message to red net
  95.     if (isWirelessTurtle == true) then
  96.       if (turtleId == nil) then
  97.         rednet.broadcast(message)
  98.       else
  99.         -- Broadcast the message (prefixed with the turtle's id)
  100.         rednet.broadcast("[".. turtleId.."] "..message)
  101.       end
  102.     end
  103.  
  104.     if (messageOutputFileName ~= nil) then
  105.       -- Open file, write message and close file (flush doesn't seem to work!)
  106.       local outputFile
  107.       if (fs.exists(messageOutputFileName) == true) then
  108.         outputFile = io.open(messageOutputFileName, "a")
  109.       else
  110.         outputFile = io.open(messageOutputFileName, "w")
  111.       end
  112.  
  113.       outputFile:write(message)
  114.       outputFile:write("\n")
  115.       outputFile:close()
  116.     end
  117.   end
  118. end
  119.  
  120. -- ********************************************************************************** --
  121. -- Ensures that the turtle has fuel
  122. -- ********************************************************************************** --
  123. function ensureFuel()
  124.  
  125.   -- Determine whether a refuel is required
  126.   local fuelLevel = turtle.getFuelLevel()
  127.   if (fuelLevel ~= "unlimited") then
  128.     if (fuelLevel < fuelLevelToRefuelAt) then
  129.       -- Need to refuel
  130.       turtle.select(16)
  131.       currentlySelectedSlot = 16
  132.       local fuelItems = turtle.getItemCount(16)
  133.  
  134.       -- Do we need to impact the emergency fuel to continue? (always  
  135.       -- keep one fuel item in slot 16)
  136.       if (fuelItems == 0) then
  137.         writeMessage("Completely out of fuel!", messageLevel.FATAL)
  138.       elseif (fuelItems == 1) then
  139.         writeMessage("Out of Fuel!", messageLevel.ERROR)
  140.         turtle.refuel()
  141.       elseif (fuelItems <= (emergencyFuelToRetain + 1)) then
  142.         writeMessage("Consuming emergency fuel supply. "..(fuelItems - 2).." emergency fuel items remain", messageLevel.WARNING)
  143.         turtle.refuel(1)
  144.       else
  145.         -- Refuel the lesser of the refuelItemsToUseWhenRefuelling and the number of items more than
  146.         -- the emergency fuel level
  147.         if (fuelItems - (emergencyFuelToRetain + 1) < refuelItemsToUseWhenRefuelling) then
  148.           turtle.refuel(fuelItems - (emergencyFuelToRetain + 1))
  149.         else
  150.           turtle.refuel(refuelItemsToUseWhenRefuelling)
  151.         end
  152.       end
  153.     end
  154.   end
  155. end        
  156.  
  157. -- ********************************************************************************** --
  158. -- Checks that the turtle has inventory space by checking for spare slots and returning
  159. -- to the starting point to empty out if it doesn't.
  160. --
  161. -- Takes the position required to move to in order to empty the turtle's inventory
  162. -- should it be full as arguments
  163. -- ********************************************************************************** --
  164. function ensureInventorySpace()
  165.  
  166.   -- If already returning to start, then don't need to do anything
  167.   if (returningToStart == false) then
  168.  
  169.     -- If the last inventory slot is full, then need to return to the start and empty
  170.     if (turtle.getItemCount(lastEmptySlot) > 0) then
  171.  
  172.       -- Return to the starting point and empty the inventory, then go back to mining
  173.       returnToStartAndUnload(true)
  174.     end
  175.   end
  176. end
  177.  
  178. -- ********************************************************************************** --
  179. -- Function to move to the starting point, call a function that is passed in
  180. -- and return to the same location (if required)
  181. -- ********************************************************************************** --
  182. function returnToStartAndUnload(returnBackToMiningPoint)
  183.  
  184.   writeMessage("returnToStartAndUnload called", messageLevel.DEBUG)
  185.   returningToStart = true
  186.   local storedX, storedY, storedZ, storedOrient
  187.   local prevMiningState = currMiningState
  188.  
  189.   if (resuming == true) then
  190.     -- Get the stored parameters from the necessary file
  191.     local resumeFile = fs.open(returnToStartFile, "r")
  192.     if (resumeFile ~= nil) then
  193.       -- Restore the parameters from the file
  194.       local beenAtZero = resumeFile.readLine()
  195.       if (beenAtZero == "y") then
  196.         haveBeenAtZeroZeroOnLayer = true
  197.       else
  198.         haveBeenAtZeroZeroOnLayer = false
  199.       end
  200.  
  201.       local miningPointFlag = resumeFile.readLine()
  202.       if (miningPointFlag == "y") then
  203.         returnBackToMiningPoint = true
  204.       else
  205.         returnBackToMiningPoint = false
  206.       end
  207.  
  208.       currX = readNumber(resumeFile)
  209.       currY = readNumber(resumeFile)
  210.       currZ = readNumber(resumeFile)
  211.       currOrient = readNumber(resumeFile)
  212.       levelToReturnTo = readNumber(resumeFile)
  213.       prevMiningState = readNumber(resumeFile)
  214.       orientationAtZeroZero = readNumber(resumeFile)
  215.       resumeFile.close()
  216.  
  217.     else
  218.       writeMessage("Failed to read return to start file", messageLevel.ERROR)
  219.     end
  220.   elseif (supportResume == true) then
  221.  
  222.     local outputFile = io.open(returnToStartFile, "w")
  223.  
  224.     if (haveBeenAtZeroZeroOnLayer == true) then
  225.       outputFile:write("y\n")
  226.     else
  227.       outputFile:write("n\n")
  228.     end
  229.     if (returnBackToMiningPoint == true) then
  230.       outputFile:write("y\n")
  231.     else
  232.       outputFile:write("n\n")
  233.     end
  234.  
  235.     outputFile:write(currX)
  236.     outputFile:write("\n")
  237.     outputFile:write(currY)
  238.     outputFile:write("\n")
  239.     outputFile:write(currZ)
  240.     outputFile:write("\n")
  241.     outputFile:write(currOrient)
  242.     outputFile:write("\n")
  243.     outputFile:write(levelToReturnTo)
  244.     outputFile:write("\n")
  245.     outputFile:write(prevMiningState)
  246.     outputFile:write("\n")
  247.     outputFile:write(orientationAtZeroZero)
  248.     outputFile:write("\n")
  249.  
  250.     outputFile:close()
  251.   end
  252.    
  253.   storedX = currX
  254.   storedY = currY
  255.   storedZ = currZ
  256.   storedOrient = currOrient
  257.  
  258.   -- Store the current location and orientation so that it can be returned to
  259.   currMiningState = miningState.EMPTYINVENTORY
  260.   writeMessage("last item count = "..turtle.getItemCount(lastEmptySlot), messageLevel.DEBUG)
  261.  
  262.   if ((turtle.getItemCount(lastEmptySlot) > 0) or (returnBackToMiningPoint == false)) then
  263.  
  264.     writeMessage("Heading back to surface", messageLevel.DEBUG)
  265.  
  266.     -- Move down to the correct layer to return via
  267.     if (currY > levelToReturnTo) then
  268.       while (currY > levelToReturnTo) do
  269.         turtleDown()
  270.       end
  271.     elseif (currY < levelToReturnTo) then
  272.       while (currY < levelToReturnTo) do
  273.         turtleUp()
  274.       end
  275.     end
  276.  
  277.     if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == direction.FORWARD)) then
  278.       -- Move back to the correct X position first
  279.       if (currX > 0) then
  280.         turtleSetOrientation(direction.LEFT)
  281.         while (currX > 0) do
  282.           turtleForward()
  283.         end
  284.       elseif (currX < 0) then
  285.         -- This should never happen
  286.         writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  287.       end
  288.  
  289.       -- Then move back to the correct Z position
  290.       if (currZ > 0) then
  291.         turtleSetOrientation(direction.BACK)
  292.         while (currZ > 0) do
  293.           turtleForward()
  294.         end
  295.       elseif (currZ < 0) then
  296.         -- This should never happen
  297.         writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  298.       end
  299.     else
  300.       -- Move back to the correct Z position first
  301.       if (currZ > 0) then
  302.         turtleSetOrientation(direction.BACK)
  303.         while (currZ > 0) do
  304.           turtleForward()
  305.         end
  306.       elseif (currZ < 0) then
  307.         -- This should never happen
  308.         writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  309.       end
  310.  
  311.       -- Then move back to the correct X position
  312.       if (currX > 0) then
  313.         turtleSetOrientation(direction.LEFT)
  314.         while (currX > 0) do
  315.           turtleForward()
  316.         end
  317.       elseif (currX < 0) then
  318.         -- This should never happen
  319.         writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  320.       end
  321.     end
  322.  
  323.     -- Return to the starting layer
  324.     if (currY < startHeight) then
  325.       while (currY < startHeight) do
  326.         turtleUp()
  327.       end
  328.     elseif (currY > startHeight) then
  329.       -- This should never happen
  330.       writeMessage("Current height is greater than start height in returnToStartAndUnload", messageLevel.ERROR)
  331.     end
  332.  
  333.     -- Empty the inventory
  334.     local slotLoop = 1
  335.  
  336.     -- Face the chest
  337.     turtleSetOrientation(direction.BACK)
  338.  
  339.     -- Loop over each of the slots (except the 16th one which stores fuel)
  340.     while (slotLoop < 16) do
  341.       -- If this is one of the slots that contains a noise block, empty all blocks except
  342.       -- one
  343.       turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  344.       if ((slotLoop <= noiseBlocksCount) or ((slotLoop == 15) and (lastEmptySlot == 14))) then
  345.         writeMessage("Dropping (n-1) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)  
  346.         if (turtle.getItemCount(slotLoop) > 0) then
  347.           turtle.drop(turtle.getItemCount(slotLoop) - 1)
  348.         end
  349.       else
  350.         -- Not a noise block, drop all of the items in this slot
  351.         writeMessage("Dropping (all) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)  
  352.         if (turtle.getItemCount(slotLoop) > 0) then
  353.           turtle.drop()
  354.         end
  355.       end
  356.      
  357.       slotLoop = slotLoop + 1
  358.     end
  359.  
  360.     -- While we are here, refill the fuel items if there is capacity
  361.     if (turtle.getItemCount(16) < 64) then
  362.       turtleSetOrientation(direction.LEFT)
  363.       turtle.select(16) -- Don't bother updating selected slot variable as it will set later in this function
  364.       local currFuelItems = turtle.getItemCount(16)
  365.       turtle.suck()
  366.       while ((currFuelItems ~= turtle.getItemCount(16)) and (turtle.getItemCount(16) < 64)) do
  367.         currFuelItems = turtle.getItemCount(16)
  368.         turtle.suck()
  369.       end
  370.  
  371.       slotLoop = noiseBlocksCount + 1
  372.       -- Have now picked up all the items that we can. If we have also picked up some
  373.       -- additional fuel in some of the other slots, then drop it again
  374.       while (slotLoop <= lastEmptySlot) do
  375.         -- Drop any items found in this slot
  376.         if (turtle.getItemCount(slotLoop) > 0) then
  377.           turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  378.           turtle.drop()
  379.         end
  380.         slotLoop = slotLoop + 1
  381.       end
  382.     end
  383.  
  384.     -- Select the 1st slot because sometimes when leaving the 15th or 16th slots selected it can result
  385.     -- in that slot being immediately filled (resulting in the turtle returning to base again too soon)
  386.     turtle.select(1)
  387.     currentlySelectedSlot = 1
  388.   end
  389.  
  390.   -- If required, move back to the point that we were mining at before returning to the start
  391.   if (returnBackToMiningPoint == true) then
  392.  
  393.     -- If resuming, refresh the starting point to be the top of the return shaft
  394.     if (resuming == true) then
  395.       currX = 0
  396.       currY = startHeight
  397.       currZ = 0
  398.       currOrient = resumeOrient
  399.     end
  400.  
  401.     -- Return back to the required layer
  402.     while (currY > levelToReturnTo) do
  403.       turtleDown()
  404.     end
  405.  
  406.     if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == direction.FORWARD)) then
  407.       -- Move back to the correct Z position first
  408.       writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  409.       if (storedZ > currZ) then
  410.         writeMessage("Orienting forward", messageLevel.DEBUG)
  411.         writeMessage("Moving in z direction", messageLevel.DEBUG)
  412.         turtleSetOrientation(direction.FORWARD)
  413.         while (storedZ > currZ) do
  414.           turtleForward()
  415.         end
  416.       elseif (storedZ < currZ) then
  417.         -- This should never happen
  418.         writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  419.       end
  420.  
  421.       -- Then move back to the correct X position
  422.       if (storedX > currX) then
  423.         writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  424.         writeMessage("Orienting right", messageLevel.DEBUG)
  425.         writeMessage("Moving in x direction", messageLevel.DEBUG)
  426.         turtleSetOrientation(direction.RIGHT)
  427.         while (storedX > currX) do
  428.           turtleForward()
  429.         end
  430.       elseif (storedX < currX) then
  431.         -- This should never happen
  432.         writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  433.       end
  434.     else
  435.       -- Move back to the correct X position first
  436.       if (storedX > currX) then
  437.         writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  438.         writeMessage("Orienting right", messageLevel.DEBUG)
  439.         writeMessage("Moving in x direction", messageLevel.DEBUG)
  440.         turtleSetOrientation(direction.RIGHT)
  441.         while (storedX > currX) do
  442.           turtleForward()
  443.         end
  444.       elseif (storedX < currX) then
  445.         -- This should never happen
  446.         writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  447.       end
  448.  
  449.       -- Then move back to the correct Z position
  450.       writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  451.       if (storedZ > currZ) then
  452.         writeMessage("Orienting forward", messageLevel.DEBUG)
  453.         writeMessage("Moving in z direction", messageLevel.DEBUG)
  454.         turtleSetOrientation(direction.FORWARD)
  455.         while (storedZ > currZ) do
  456.           turtleForward()
  457.         end
  458.       elseif (storedZ < currZ) then
  459.         -- This should never happen
  460.         writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  461.       end
  462.     end
  463.  
  464.     -- Move back to the correct layer
  465.     if (storedY < currY) then
  466.       while (storedY < currY) do
  467.         turtleDown()
  468.       end
  469.     elseif (storedY > currY) then
  470.       while (storedY > currY) do
  471.         turtleUp()
  472.       end
  473.     end
  474.  
  475.     -- Finally, set the correct orientation
  476.     turtleSetOrientation(storedOrient)
  477.  
  478.     writeMessage("Have returned to the mining point", messageLevel.DEBUG)
  479.   end
  480.  
  481.   -- Store the current location and orientation so that it can be returned to
  482.   currMiningState = prevMiningState
  483.  
  484.   returningToStart = false
  485.  
  486. end
  487.  
  488. -- ********************************************************************************** --
  489. -- Empties a chest's contents
  490. -- ********************************************************************************** --
  491. function emptyChest(suckFn)
  492.  
  493.   local prevInventoryCount = {}
  494.   local inventoryLoop
  495.   local chestEmptied = false
  496.  
  497.   -- Record the number of items in each of the inventory slots
  498.   for inventoryLoop = 1, 16 do
  499.     prevInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  500.   end
  501.  
  502.   while (chestEmptied == false) do
  503.     -- Pick up the next item
  504.     suckFn()
  505.  
  506.     -- Determine the number of items in each of the inventory slots now
  507.     local newInventoryCount = {}
  508.     for inventoryLoop = 1, 16 do
  509.       newInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  510.     end
  511.  
  512.     -- Now, determine whether there have been any items taken from the chest
  513.     local foundDifferentItemCount = false
  514.     inventoryLoop = 1
  515.     while ((foundDifferentItemCount == false) and (inventoryLoop <= 16)) do
  516.       if (prevInventoryCount[inventoryLoop] ~= newInventoryCount[inventoryLoop]) then
  517.         foundDifferentItemCount = true
  518.       else
  519.         inventoryLoop = inventoryLoop + 1
  520.       end
  521.     end
  522.    
  523.     -- If no items have been found with a different item count, then the chest has been emptied
  524.     chestEmptied = not foundDifferentItemCount
  525.  
  526.     if (chestEmptied == false) then
  527.       prevInventoryCount = newInventoryCount
  528.       -- Check that there is sufficient inventory space as may have picked up a block
  529.       ensureInventorySpace()
  530.     end
  531.   end
  532.  
  533.   writeMessage("Finished emptying chest", messageLevel.DEBUG)
  534. end
  535.  
  536. -- ********************************************************************************** --
  537. -- Write the current location to a file
  538. -- ********************************************************************************** --
  539. function saveLocation()
  540.  
  541.   -- Write the x, y, z and orientation to the file
  542.   if ((supportResume == true) and (resuming == false)) then
  543.     local outputFile = io.open(oreQuarryLocation, "w")
  544.     outputFile:write(currMiningState)
  545.     outputFile:write("\n")
  546.     outputFile:write(currX)
  547.     outputFile:write("\n")
  548.     outputFile:write(currY)
  549.     outputFile:write("\n")
  550.     outputFile:write(currZ)
  551.     outputFile:write("\n")
  552.     outputFile:write(currOrient)
  553.     outputFile:write("\n")
  554.     outputFile:close()
  555.   end
  556.  
  557. end
  558.  
  559. -- ********************************************************************************** --
  560. -- If the turtle is resuming and the current co-ordinates, orientation and
  561. -- mining state have been matched, then no longer resuming
  562. -- ********************************************************************************** --
  563. function updateResumingFlag()
  564.  
  565.   if (resuming == true) then
  566.     if ((resumeMiningState == currMiningState) and (resumeX == currX) and (resumeY == currY) and (resumeZ == currZ) and (resumeOrient == currOrient)) then
  567.       resuming = false
  568.     end
  569.   end
  570.  
  571. end
  572.  
  573. -- ********************************************************************************** --
  574. -- Generic function to move the Turtle (pushing through any gravel or other
  575. -- things such as mobs that might get in the way).
  576. --
  577. -- The only thing that should stop the turtle moving is bedrock. Where this is
  578. -- found, the function will return after 15 seconds returning false
  579. -- ********************************************************************************** --
  580. function moveTurtle(moveFn, detectFn, digFn, attackFn, compareFn, suckFn, maxDigCount, newX, newY, newZ)
  581.  
  582.   local moveSuccess = false
  583.  
  584.   -- If we are resuming, then don't do anything in this function other than updating the
  585.   -- co-ordinates as if the turtle had moved
  586.   if (resuming == true) then
  587.     -- Set the move success to true (but don't move) - unless this is below bedrock level
  588.     -- in which case return false
  589.     if (currY <= 0) then
  590.       moveSuccess = false
  591.     else
  592.       moveSuccess = true
  593.     end
  594.  
  595.     -- Update the co-ordinates to reflect the movement
  596.     currX = newX
  597.     currY = newY
  598.     currZ = newZ
  599.  
  600.   else
  601.     local prevX, prevY, prevZ
  602.     prevX = currX
  603.     prevY = currY
  604.     prevZ = currZ
  605.  
  606.     ensureFuel()
  607.  
  608.     -- Flag to determine whether digging has been tried yet. If it has
  609.     -- then pause briefly before digging again to allow sand or gravel to
  610.     -- drop
  611.     local digCount = 0
  612.  
  613.     if (lastMoveNeededDig == false) then
  614.       -- Didn't need to dig last time the turtle moved, so try moving first
  615.  
  616.       currX = newX
  617.       currY = newY
  618.       currZ = newZ
  619.       saveLocation()
  620.  
  621.       moveSuccess = moveFn()
  622.  
  623.       -- If move failed, update the co-ords back to the previous co-ords
  624.       if (moveSuccess == false) then
  625.         currX = prevX
  626.         currY = prevY
  627.         currZ = prevZ
  628.         saveLocation()
  629.       end
  630.  
  631.       -- Don't need to set the last move needed dig. It is already false, if
  632.       -- move success is now true, then it won't be changed
  633.     else    
  634.       -- If we are looking for chests, then check that this isn't a chest before trying to dig it
  635.       if (lookForChests == true) then
  636.         if (isNoiseBlock(compareFn) == false) then
  637.           if (detectFn() == true) then
  638.             -- Determine if it is a chest before digging it
  639.             if (isChestBlock(compareFn) == true) then
  640.               -- Have found a chest, empty it before continuing
  641.               emptyChest (suckFn)
  642.             end
  643.           end
  644.         end
  645.       end
  646.  
  647.       -- Try to dig (without doing a detect as it is quicker)
  648.       local digSuccess = digFn()
  649.       if (digSuccess == true) then
  650.         digCount = 1
  651.       end
  652.  
  653.       currX = newX
  654.       currY = newY
  655.       currZ = newZ
  656.       saveLocation()
  657.  
  658.       moveSuccess = moveFn()
  659.  
  660.       if (moveSuccess == true) then
  661.         lastMoveNeededDig = digSuccess
  662.       else
  663.         currX = prevX
  664.         currY = prevY
  665.         currZ = prevZ
  666.         saveLocation()
  667.       end
  668.  
  669.     end
  670.  
  671.     -- Loop until we've successfully moved
  672.     if (moveSuccess == false) then
  673.       while ((moveSuccess == false) and (digCount < maxDigCount)) do
  674.  
  675.         -- If there is a block in front, dig it
  676.         if (detectFn() == true) then
  677.        
  678.             -- If we've already tried digging, then pause before digging again to let
  679.             -- any sand or gravel drop, otherwise check for a chest before digging
  680.             if(digCount == 0) then
  681.               -- Am about to dig a block - check that it is not a chest if necessary
  682.               -- If we are looking for chests, then check that this isn't a chest before moving
  683.               if (lookForChests == true) then
  684.                 if (isNoiseBlock(compareFn) == false) then
  685.                   if (detectFn() == true) then
  686.                     -- Determine if it is a chest before digging it
  687.                     if (isChestBlock(compareFn) == true) then
  688.                       -- Have found a chest, empty it before continuing
  689.                       emptyChest (suckFn)
  690.                     end
  691.                   end
  692.                 end
  693.               end
  694.             else
  695.               sleep(0.1)
  696.             end
  697.  
  698.             digFn()
  699.             digCount = digCount + 1
  700.         else
  701.            -- Am being stopped from moving by a mob, attack it
  702.            attackFn()
  703.         end
  704.  
  705.         currX = newX
  706.         currY = newY
  707.         currZ = newZ
  708.         saveLocation()
  709.    
  710.         -- Try the move again
  711.         moveSuccess = moveFn()
  712.  
  713.         if (moveSuccess == false) then
  714.           currX = prevX
  715.           currY = prevY
  716.           currZ = prevZ
  717.           saveLocation()
  718.         end
  719.       end
  720.  
  721.       if (digCount == 0) then
  722.         lastMoveNeededDig = false
  723.       else
  724.         lastMoveNeededDig = true
  725.       end
  726.       sleep(0)
  727.     end
  728.   end
  729.  
  730.   -- If we are resuming and the current co-ordinates and orientation are the resume point
  731.   -- then are no longer resuming
  732.   if (moveSuccess == true) then
  733.     updateResumingFlag()
  734.   end
  735.  
  736.   -- Return the move success
  737.   return moveSuccess
  738.  
  739. end
  740.  
  741. -- ********************************************************************************** --
  742. -- Move the turtle forward one block (updating the turtle's position)
  743. -- ********************************************************************************** --
  744. function turtleForward()
  745.  
  746.   -- Determine the new co-ordinate that the turtle will be moving to
  747.   local newX, newZ
  748.  
  749.   -- Update the current co-ordinates
  750.   if (currOrient == direction.FORWARD) then
  751.     newZ = currZ + 1
  752.     newX = currX
  753.   elseif (currOrient == direction.LEFT) then
  754.     newX = currX - 1
  755.     newZ = currZ
  756.   elseif (currOrient == direction.BACK) then
  757.     newZ = currZ - 1
  758.     newX = currX
  759.   elseif (currOrient == direction.RIGHT) then
  760.     newX = currX + 1
  761.     newZ = currZ
  762.   else
  763.     writeMessage ("Invalid currOrient in turtleForward function", messageLevel.ERROR)
  764.   end
  765.  
  766.   local returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  767.  
  768.   if (returnVal == true) then
  769.     -- Check that there is sufficient inventory space as may have picked up a block
  770.     ensureInventorySpace()
  771.   end
  772.  
  773.   return returnVal
  774. end
  775.  
  776. -- ********************************************************************************** --
  777. -- Move the turtle up one block (updating the turtle's position)
  778. -- ********************************************************************************** --
  779. function turtleUp()
  780.  
  781.   local returnVal = moveTurtle(turtle.up, turtle.detectUp, turtle.digUp, turtle.attackUp, turtle.compareUp, turtle.suckUp, maximumGravelStackSupported, currX, currY + 1, currZ)
  782.  
  783.   if (returnVal == true) then
  784.     -- Check that there is sufficient inventory space as may have picked up a block
  785.     ensureInventorySpace()
  786.   end
  787.  
  788.   return returnVal
  789. end
  790.  
  791. -- ********************************************************************************** --
  792. -- Move the turtle down one block (updating the turtle's position)
  793. -- ********************************************************************************** --
  794. function turtleDown()
  795.  
  796.   local returnVal = moveTurtle(turtle.down, turtle.detectDown, turtle.digDown, turtle.attackDown, turtle.compareDown, turtle.suckDown, 1, currX, currY - 1, currZ)
  797.  
  798.   if (returnVal == true) then
  799.     -- Check that there is sufficient inventory space as may have picked up a block
  800.     ensureInventorySpace()
  801.   end
  802.  
  803.   return returnVal
  804.  
  805. end
  806.  
  807. -- ********************************************************************************** --
  808. -- Move the turtle back one block (updating the turtle's position)
  809. -- ********************************************************************************** --
  810. function turtleBack()
  811.  
  812.   -- Assume that the turtle will move, and switch the co-ords back if it doesn't
  813.   -- (do this so that we can write the co-ords to a file before moving)
  814.   local newX, newZ
  815.   local prevX, prevZ
  816.   prevX = currX
  817.   prevZ = currZ
  818.  
  819.   -- Update the current co-ordinates
  820.   if (currOrient == direction.FORWARD) then
  821.     newZ = currZ - 1
  822.     newX = currX
  823.   elseif (currOrient == direction.LEFT) then
  824.     newX = currX + 1
  825.     newZ = currZ
  826.   elseif (currOrient == direction.BACK) then
  827.     newZ = currZ + 1
  828.     newX = currX
  829.   elseif (currOrient == direction.RIGHT) then
  830.     newX = currX - 1
  831.     newZ = currZ
  832.   else
  833.     writeMessage ("Invalid currOrient in turtleBack function", messageLevel.ERROR)
  834.   end
  835.  
  836.   -- First try to move back using the standard function
  837.  
  838.   currX = newX
  839.   currZ = newZ
  840.   saveLocation()
  841.   local returnVal = turtle.back()
  842.  
  843.   if (returnVal == false) then
  844.     -- Didn't move. Reset the co-ordinates to the previous value
  845.     currX = prevX
  846.     currZ = prevZ
  847.  
  848.     -- Reset the location back to the previous location (because the turn takes 0.8 of a second
  849.     -- so could be stopped before getting to the forward function)
  850.     saveLocation()
  851.  
  852.     turtle.turnRight()
  853.     turtle.turnRight()
  854.  
  855.     -- Try to move by using the forward function (note, the orientation will be set as
  856.     -- the same way as this function started because if the function stops, that is the
  857.     -- direction that we want to consider the turtle to be pointing)
  858.  
  859.     returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  860.  
  861.     turtle.turnRight()
  862.     turtle.turnRight()
  863.   end
  864.  
  865.   if (returnVal == true) then
  866.     -- Check that there is sufficient inventory space as may have picked up a block
  867.     ensureInventorySpace()
  868.   end
  869.    
  870.   return returnVal
  871. end
  872.  
  873. -- ********************************************************************************** --
  874. -- Turns the turtle (updating the current orientation at the same time)
  875. -- ********************************************************************************** --
  876. function turtleTurn(turnDir)
  877.  
  878.   if (turnDir == direction.LEFT) then
  879.     if (currOrient == direction.FORWARD) then
  880.       currOrient = direction.LEFT
  881.     elseif (currOrient == direction.LEFT) then
  882.       currOrient = direction.BACK
  883.     elseif (currOrient == direction.BACK) then
  884.       currOrient = direction.RIGHT
  885.     elseif (currOrient == direction.RIGHT) then
  886.       currOrient = direction.FORWARD
  887.     else
  888.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  889.     end
  890.  
  891.     -- If we are resuming, just check to see whether have reached the resume point, otherwise
  892.     -- turn
  893.     if (resuming == true) then
  894.       updateResumingFlag()
  895.     else
  896.       -- Write the new orientation and turn
  897.       saveLocation()
  898.       turtle.turnLeft()
  899.     end
  900.  
  901.   elseif (turnDir == direction.RIGHT) then
  902.     if (currOrient == direction.FORWARD) then
  903.       currOrient = direction.RIGHT
  904.     elseif (currOrient == direction.LEFT) then
  905.       currOrient = direction.FORWARD
  906.     elseif (currOrient == direction.BACK) then
  907.       currOrient = direction.LEFT
  908.     elseif (currOrient == direction.RIGHT) then
  909.       currOrient = direction.BACK
  910.     else
  911.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  912.     end
  913.  
  914.     -- If we are resuming, just check to see whether have reached the resume point, otherwise
  915.     -- turn
  916.     if (resuming == true) then
  917.       updateResumingFlag()
  918.  
  919.       writeMessage("["..currMiningState..", "..currX..", "..currY..", "..currZ..", "..currOrient.."]", messageLevel.DEBUG)
  920.     else
  921.       -- Write the new orientation and turn
  922.       saveLocation()
  923.       turtle.turnRight()
  924.     end
  925.   else
  926.     writeMessage ("Invalid turnDir in turtleTurn function", messageLevel.ERROR)
  927.   end
  928. end
  929.  
  930. -- ********************************************************************************** --
  931. -- Sets the turtle to a specific orientation, irrespective of its current orientation
  932. -- ********************************************************************************** --
  933. function turtleSetOrientation(newOrient)
  934.  
  935.   if (currOrient ~= newOrient) then
  936.     if (currOrient == direction.FORWARD) then
  937.       if (newOrient == direction.RIGHT) then
  938.         currOrient = newOrient
  939.  
  940.         -- If resuming, check whether the resume point has been reached, otherwise turn
  941.         if (resuming == true) then
  942.           updateResumingFlag()
  943.         else
  944.           -- Write the new orientation and turn
  945.           saveLocation()
  946.           turtle.turnRight()
  947.         end
  948.       elseif (newOrient == direction.BACK) then
  949.         currOrient = newOrient
  950.  
  951.         -- If resuming, check whether the resume point has been reached, otherwise turn
  952.         if (resuming == true) then
  953.           updateResumingFlag()
  954.         else
  955.           -- Write the new orientation and turn
  956.           saveLocation()
  957.           turtle.turnRight()
  958.           turtle.turnRight()
  959.         end
  960.       elseif (newOrient == direction.LEFT) then
  961.         currOrient = newOrient
  962.  
  963.         -- If resuming, check whether the resume point has been reached, otherwise turn
  964.         if (resuming == true) then
  965.           updateResumingFlag()
  966.         else
  967.           -- Write the new orientation and turn
  968.           saveLocation()
  969.           turtle.turnLeft()
  970.         end
  971.       else
  972.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  973.       end
  974.     elseif (currOrient == direction.RIGHT) then
  975.       if (newOrient == direction.BACK) then
  976.         currOrient = newOrient
  977.  
  978.         -- If resuming, check whether the resume point has been reached, otherwise turn
  979.         if (resuming == true) then
  980.           updateResumingFlag()
  981.         else
  982.           -- Write the new orientation and turn
  983.           saveLocation()
  984.           turtle.turnRight()
  985.         end
  986.       elseif (newOrient == direction.LEFT) then
  987.         currOrient = newOrient
  988.  
  989.         -- If resuming, check whether the resume point has been reached, otherwise turn
  990.         if (resuming == true) then
  991.           updateResumingFlag()
  992.         else
  993.           -- Write the new orientation and turn
  994.           saveLocation()
  995.           turtle.turnRight()
  996.           turtle.turnRight()
  997.         end
  998.       elseif (newOrient == direction.FORWARD) then
  999.         currOrient = newOrient
  1000.  
  1001.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1002.         if (resuming == true) then
  1003.           updateResumingFlag()
  1004.         else
  1005.           -- Write the new orientation and turn
  1006.           saveLocation()
  1007.           turtle.turnLeft()
  1008.         end
  1009.       else
  1010.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1011.       end
  1012.     elseif (currOrient == direction.BACK) then
  1013.       if (newOrient == direction.LEFT) then
  1014.         currOrient = newOrient
  1015.  
  1016.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1017.         if (resuming == true) then
  1018.           updateResumingFlag()
  1019.         else
  1020.           -- Write the new orientation and turn
  1021.           saveLocation()
  1022.           turtle.turnRight()
  1023.         end
  1024.       elseif (newOrient == direction.FORWARD) then
  1025.         currOrient = newOrient
  1026.  
  1027.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1028.         if (resuming == true) then
  1029.           updateResumingFlag()
  1030.         else
  1031.           -- Write the new orientation and turn
  1032.           saveLocation()
  1033.           turtle.turnRight()
  1034.           turtle.turnRight()
  1035.         end
  1036.       elseif (newOrient == direction.RIGHT) then
  1037.         currOrient = newOrient
  1038.  
  1039.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1040.         if (resuming == true) then
  1041.           updateResumingFlag()
  1042.         else
  1043.           -- Write the new orientation and turn
  1044.           saveLocation()
  1045.           turtle.turnLeft()
  1046.         end
  1047.       else
  1048.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1049.       end
  1050.     elseif (currOrient == direction.LEFT) then
  1051.       if (newOrient == direction.FORWARD) then
  1052.         currOrient = newOrient
  1053.  
  1054.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1055.         if (resuming == true) then
  1056.           updateResumingFlag()
  1057.         else
  1058.           -- Write the new orientation and turn
  1059.           saveLocation()
  1060.           turtle.turnRight()
  1061.         end
  1062.       elseif (newOrient == direction.RIGHT) then
  1063.         currOrient = newOrient
  1064.  
  1065.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1066.         if (resuming == true) then
  1067.           updateResumingFlag()
  1068.         else
  1069.           -- Write the new orientation and turn
  1070.           saveLocation()
  1071.           turtle.turnRight()
  1072.           turtle.turnRight()
  1073.         end
  1074.       elseif (newOrient == direction.BACK) then
  1075.         currOrient = newOrient
  1076.  
  1077.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1078.         if (resuming == true) then
  1079.           updateResumingFlag()
  1080.         else
  1081.           -- Write the new orientation and turn
  1082.           saveLocation()
  1083.           turtle.turnLeft()
  1084.         end
  1085.       else
  1086.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1087.       end
  1088.     else
  1089.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  1090.     end
  1091.   end
  1092. end
  1093.  
  1094. -- ********************************************************************************** --
  1095. -- Determines if a particular block is considered a noise block or not. A noise
  1096. -- block is one that is a standard block in the game (stone, dirt, gravel etc.) and
  1097. -- is one to ignore as not being an ore. Function works by comparing the block
  1098. -- in question against a set of blocks in the turtle's inventory which are known not to
  1099. -- be noise blocks. Param is the function to use to compare the block for a noise block
  1100. -- ********************************************************************************** --
  1101. function isNoiseBlock(compareFn)
  1102.  
  1103.   -- Consider air to be a noise block
  1104.   local returnVal = false
  1105.  
  1106.   if (resuming == true) then
  1107.     returnVal = true
  1108.   else
  1109.     local seamLoop = 1
  1110.     local prevSelectedSlot  
  1111.  
  1112.     -- If the currently selected slot is a noise block, then compare against this first
  1113.     -- so that the slot doesn't need to be selected again (there is a 0.05s cost to do
  1114.     -- this even if it is the currently selected slot)
  1115.     if (currentlySelectedSlot <= noiseBlocksCount) then
  1116.       returnVal = compareFn()
  1117.     end
  1118.  
  1119.     if (returnVal == false) then
  1120.       prevSelectedSlot = currentlySelectedSlot
  1121.       while((returnVal == false) and (seamLoop <= noiseBlocksCount)) do
  1122.         if (seamLoop ~= prevSelectedSlot) then
  1123.           turtle.select(seamLoop)
  1124.           currentlySelectedSlot = seamLoop
  1125.           returnVal = compareFn()
  1126.         end
  1127.         seamLoop = seamLoop + 1
  1128.       end
  1129.     end
  1130.   end
  1131.  
  1132.   -- Return the calculated value
  1133.   return returnVal
  1134.  
  1135. end
  1136.  
  1137. -- ********************************************************************************** --
  1138. -- Determines if a particular block is a chest. Returns false if it is not a chest
  1139. -- or chests are not being detected
  1140. -- ********************************************************************************** --
  1141. function isChestBlock(compareFn)
  1142.  
  1143.   -- Check the block in the appropriate direction to see whether it is a chest. Only
  1144.   -- do this if we are looking for chests
  1145.   local returnVal = false
  1146.   if (lookForChests == true) then
  1147.     turtle.select(15)
  1148.     currentlySelectedSlot = 15
  1149.     returnVal = compareFn()
  1150.   end
  1151.  
  1152.   -- Return the calculated value
  1153.   return returnVal
  1154.  
  1155. end
  1156.  
  1157. -- ********************************************************************************** --
  1158. -- Function to calculate the number of non seam blocks in the turtle's inventory. This
  1159. -- is all of the blocks at the start of the inventory (before the first empty slot is
  1160. -- found
  1161. -- ********************************************************************************** --
  1162. function determineNoiseBlocksCountCount()
  1163.   -- Determine the location of the first empty inventory slot. All items before this represent
  1164.   -- noise items.
  1165.   local foundFirstBlankInventorySlot = false
  1166.   noiseBlocksCount = 1
  1167.   while ((noiseBlocksCount < 16) and (foundFirstBlankInventorySlot == false)) do
  1168.     if (turtle.getItemCount(noiseBlocksCount) > 0) then
  1169.       noiseBlocksCount = noiseBlocksCount + 1
  1170.     else
  1171.       foundFirstBlankInventorySlot = true
  1172.     end
  1173.   end
  1174.   noiseBlocksCount = noiseBlocksCount - 1
  1175.  
  1176.   -- Determine whether a chest was provided, and hence whether we should support
  1177.   -- looking for chests
  1178.   if (turtle.getItemCount(15) > 0) then
  1179.     lookForChests = true
  1180.     lastEmptySlot = 14
  1181.     miningOffset = 0
  1182.     writeMessage("Looking for chests...", messageLevel.DEBUG)
  1183.   else
  1184.     lastEmptySlot = 15
  1185.     miningOffset = 1
  1186.     writeMessage("Ignoring chests...", messageLevel.DEBUG)
  1187.   end
  1188. end
  1189.  
  1190. -- ********************************************************************************** --
  1191. -- Creates a quarry mining out only ores and leaving behind any noise blocks
  1192. -- ********************************************************************************** --
  1193. function createQuarry()
  1194.  
  1195.   -- Determine the top mining layer layer. The turtle mines in layers of 3, and the bottom layer
  1196.   -- is the layer directly above bedrock.
  1197.   --
  1198.   -- The actual layer that the turtle operates in is the middle of these three layers,
  1199.   -- so determine the top layer
  1200.   local topMiningLayer = startHeight + ((bottomLayer - startHeight - 2) % 3) - 1 + miningOffset
  1201.  
  1202.   -- If the top layer is up, then ignore it and move to the next layer
  1203.   if (topMiningLayer > currY) then
  1204.     topMiningLayer = topMiningLayer - 3
  1205.   end
  1206.  
  1207.   local startedLayerToRight = true -- Only used where the quarry is of an odd width
  1208.  
  1209.   -- Loop over each mining row
  1210.   local miningLevel
  1211.   for miningLevel = (bottomLayer + miningOffset), topMiningLayer, 3 do
  1212.     writeMessage("Mining Layer: "..miningLevel, messageLevel.INFO)
  1213.     haveBeenAtZeroZeroOnLayer = false
  1214.  
  1215.     -- While the initial shaft is being dug out, set the level to return to in order to unload
  1216.     -- to the just take the turtle straight back up
  1217.     if (miningLevel == (bottomLayer + miningOffset)) then
  1218.       levelToReturnTo = startHeight
  1219.     end
  1220.  
  1221.     -- Move to the correct level to start mining
  1222.     if (currY > miningLevel) then
  1223.       while (currY > miningLevel) do
  1224.         turtleDown()
  1225.       end
  1226.     elseif (currY < miningLevel) then
  1227.       while (currY < miningLevel) do
  1228.         turtleUp()
  1229.       end
  1230.     end
  1231.  
  1232.     -- Am now mining the levels (update the mining state to reflect that fact)
  1233.     currMiningState = miningState.LAYER
  1234.  
  1235.     -- Set the layer to return via when returning to the surface as the one below the currently
  1236.     -- mined one
  1237.     if (miningLevel == (bottomLayer + miningOffset)) then
  1238.       levelToReturnTo = (bottomLayer + miningOffset)
  1239.     else
  1240.       levelToReturnTo = miningLevel - 3
  1241.     end
  1242.  
  1243.     -- Move turtle into the correct orientation to start mining (if this is the
  1244.     -- first row to be mined, then don't need to turn, otherwise turn towards the next
  1245.     -- mining section)
  1246.  
  1247.     writeMessage("Mining Level: "..miningLevel..", Bottom Layer: "..bottomLayer..", Mining Offset: "..miningOffset, messageLevel.DEBUG)
  1248.  
  1249.     if (miningLevel > (bottomLayer + miningOffset)) then
  1250.       -- Turn towards the next mining layer
  1251.       if (quarryWidth % 2 == 0) then
  1252.         -- An even width quarry, always turn right
  1253.         turtleTurn(direction.RIGHT)
  1254.       else
  1255.         -- Turn the opposite direction to that which we turned before
  1256.         if (startedLayerToRight == true) then
  1257.           turtleTurn(direction.LEFT)
  1258.           startedLayerToRight = false
  1259.         else
  1260.           turtleTurn(direction.RIGHT)
  1261.           startedLayerToRight = true
  1262.         end
  1263.       end
  1264.     end
  1265.  
  1266.     local mineRows
  1267.     local onNearSideOfQuarry = true
  1268.     local diggingAway = true
  1269.     for mineRows = 1, quarryWidth do
  1270.  
  1271.       -- If this is not the first row, then get into position to mine the next row
  1272.       if ((mineRows == 1) and (lookForChests == false)) then
  1273.         -- Not looking for chests, check the block below for being an ore. Only do this
  1274.         -- if we're not looking for chests since the program doesn't support chests in
  1275.         -- bedrock
  1276.         if (isNoiseBlock(turtle.compareDown) == false) then
  1277.           turtle.digDown()
  1278.           ensureInventorySpace()
  1279.         end
  1280.       elseif (mineRows > 1) then
  1281.         -- Move into position for mining the next row
  1282.         if (onNearSideOfQuarry == diggingAway) then
  1283.           if (startedLayerToRight == true) then
  1284.             turtleTurn(direction.LEFT)
  1285.           else
  1286.             turtleTurn(direction.RIGHT)
  1287.           end
  1288.         else
  1289.           if (startedLayerToRight == true) then
  1290.             turtleTurn(direction.RIGHT)
  1291.           else
  1292.             turtleTurn(direction.LEFT)
  1293.           end
  1294.         end
  1295.  
  1296.         turtleForward()
  1297.  
  1298.         -- Before making the final turn, check the block below. Do this
  1299.         -- now because if it is a chest, then we want to back up and
  1300.         -- approach it from the side (so that we don't lose items if we
  1301.         -- have to return to the start through it).
  1302.         --
  1303.         -- This is the point at which it is safe to back up without moving
  1304.         -- out of the quarry area (unless at bedrock in which case don't bother
  1305.         -- as we'll be digging down anyway)
  1306.         if (miningLevel ~= bottomLayer) then
  1307.           if (isNoiseBlock(turtle.compareDown) == false) then
  1308.             -- If we are not looking for chests, then just dig it (it takes
  1309.             -- less time to try to dig and fail as it does to do detect and
  1310.             -- only dig if there is a block there)
  1311.             if (lookForChests == false) then
  1312.               turtle.digDown()
  1313.               ensureInventorySpace()
  1314.             elseif (turtle.detectDown() == true) then
  1315.               if (isChestBlock(turtle.compareDown) == true) then
  1316.                 -- There is a chest block below. Move back and approach
  1317.                 -- from the side to ensure that we don't need to return to
  1318.                 -- start through the chest itself (potentially losing items)
  1319.                 turtleBack()
  1320.                 turtleDown()
  1321.                 currMiningState = miningState.EMPTYCHESTDOWN
  1322.                 emptyChest(turtle.suck)
  1323.                 currMiningState = miningState.LAYER
  1324.                 turtleUp()
  1325.                 turtleForward()
  1326.                 turtle.digDown()
  1327.                 ensureInventorySpace()
  1328.               else
  1329.                 turtle.digDown()
  1330.                 ensureInventorySpace()
  1331.               end
  1332.             end
  1333.           end
  1334.         end
  1335.  
  1336.         -- Move into final position for mining the next row
  1337.         if (onNearSideOfQuarry == diggingAway) then
  1338.           if (startedLayerToRight == true) then
  1339.             turtleTurn(direction.LEFT)
  1340.           else
  1341.             turtleTurn(direction.RIGHT)
  1342.           end
  1343.         else
  1344.           if (startedLayerToRight == true) then
  1345.             turtleTurn(direction.RIGHT)
  1346.           else
  1347.             turtleTurn(direction.LEFT)
  1348.           end
  1349.         end
  1350.       end
  1351.  
  1352.       -- Dig to the other side of the quarry
  1353.       local blocksMined
  1354.       for blocksMined = 0, (quarryWidth - 1) do
  1355.         if (blocksMined > 0) then
  1356.           -- Only move forward if this is not the first space
  1357.           turtleForward()
  1358.         end
  1359.  
  1360.         -- If the current block is (0,0), then record the fact that the
  1361.         -- turtle has been through this block and what it's orientation was and update the layer
  1362.         -- that it should return via to get back to the surface (it no longer needs to go down
  1363.         -- a level to prevent losing ores).
  1364.         if ((currX == 0) and (currZ == 0)) then
  1365.           -- Am at (0, 0). Remember this, and what direction I was facing so that the quickest route
  1366.           -- to the surface can be taken
  1367.           levelToReturnTo = miningLevel
  1368.           haveBeenAtZeroZeroOnLayer = true
  1369.           orientationAtZeroZero = currOrient
  1370.         end
  1371.  
  1372.         -- If currently at bedrock, just move down until the turtle can't go any
  1373.         -- further. This allows the blocks within the bedrock to be mined
  1374.         if (miningLevel == bottomLayer) then
  1375.           -- Temporarily turn off looking for chests to increase bedrock mining speed (this
  1376.           -- means that the program doesn't support chests below level 5 - but I think
  1377.           -- they they don't exist anyway)
  1378.           local lookForChestsPrev = lookForChests
  1379.           lookForChests = false
  1380.  
  1381.           -- Manually set the flag to determine whether the turtle should try to move first or
  1382.           -- dig first. At bedrock, is very rarely any space
  1383.  
  1384.           -- Just above bedrock layer, dig down until can't dig any lower, and then
  1385.           -- come back up. This replicates how the quarry functions
  1386.           lastMoveNeededDig = true
  1387.           local moveDownSuccess = turtleDown()
  1388.           while (moveDownSuccess == true) do
  1389.             moveDownSuccess = turtleDown()
  1390.           end
  1391.  
  1392.           -- Know that we are moving back up through air, therefore set the flag to force the
  1393.           -- turtle to try moving first
  1394.           lastMoveNeededDig = false
  1395.  
  1396.           -- Have now hit bedrock, move back to the mining layer
  1397.           while (currY < bottomLayer) do
  1398.             turtleUp()
  1399.           end
  1400.  
  1401.           -- Now back at the level above bedrock, again reset the flag to tell the turtle to
  1402.           -- try digging again (because it is rare to find air at bedrock level)
  1403.           lastMoveNeededDig = false
  1404.  
  1405.           -- Reset the look for chests value
  1406.           lookForChests = lookForChestsPrev
  1407.         elseif ((blocksMined > 0) and ((currX ~= 0) or (currZ ~= 0))) then
  1408.           -- This isn't the first block of the row, nor are we at (0, 0) so we need to check the
  1409.           -- block below
  1410.  
  1411.           -- Check the block down for being a noise block (don't need to check the first
  1412.           -- block as it has already been checked in the outer loop)
  1413.           if (isNoiseBlock(turtle.compareDown) == false) then
  1414.             -- If we are not looking for chests, then just dig it (it takes
  1415.             -- less time to try to dig and fail as it does to do detect and
  1416.             -- only dig if there is a block there)
  1417.             if (lookForChests == false) then
  1418.               turtle.digDown()
  1419.               ensureInventorySpace()
  1420.             elseif (turtle.detectDown() == true) then
  1421.               if (isChestBlock(turtle.compareDown) == true) then
  1422.                 -- There is a chest block below. Move back and approach
  1423.                 -- from the side to ensure that we don't need to return to
  1424.                 -- start through the chest itself (potentially losing items)
  1425.                 turtleBack()
  1426.                 currMiningState = miningState.EMPTYCHESTDOWN
  1427.                 turtleDown()
  1428.                 emptyChest(turtle.suck)
  1429.                 currMiningState = miningState.LAYER
  1430.                 turtleUp()
  1431.                 turtleForward()
  1432.                 turtle.digDown()
  1433.                 ensureInventorySpace()
  1434.               else
  1435.                 turtle.digDown()
  1436.                 ensureInventorySpace()
  1437.               end
  1438.             end
  1439.           end
  1440.         end
  1441.        
  1442.         -- Check the block above for ores (if we're not a (0, 0) in which case
  1443.         -- we know it's air)
  1444.         if ((currX ~= 0) or (currZ ~= 0)) then
  1445.           if (isNoiseBlock(turtle.compareUp) == false) then
  1446.             -- If we are not looking for chests, then just dig it (it takes
  1447.             -- less time to try to dig and fail as it does to do detect and
  1448.             -- only dig if there is a block there)
  1449.             if (lookForChests == false) then
  1450.               turtle.digUp()
  1451.               ensureInventorySpace()
  1452.             elseif (turtle.detectUp() == true) then
  1453.               -- Determine if it is a chest before digging it
  1454.               if (isChestBlock(turtle.compareUp) == true) then
  1455.                 -- There is a chest block above. Empty it before digging it
  1456.                 emptyChest(turtle.suckUp)
  1457.                 turtle.digUp()
  1458.                 ensureInventorySpace()
  1459.               else
  1460.                 turtle.digUp()
  1461.                 ensureInventorySpace()
  1462.               end
  1463.             end
  1464.           end
  1465.         end
  1466.       end
  1467.  
  1468.       -- Am now at the other side of the quarry
  1469.       onNearSideOfQuarry = not onNearSideOfQuarry
  1470.     end
  1471.  
  1472.     -- If we were digging away from the starting point, will be digging
  1473.     -- back towards it on the next layer
  1474.     diggingAway = not diggingAway
  1475.   end
  1476.  
  1477.   -- Return to the start
  1478.   returnToStartAndUnload(false)
  1479.  
  1480.   -- Face forward
  1481.   turtleSetOrientation(direction.FORWARD)
  1482. end
  1483.  
  1484. -- ********************************************************************************** --
  1485. -- Reads the next number from a given file
  1486. -- ********************************************************************************** --
  1487. function readNumber(inputFile)
  1488.  
  1489.   local returnVal
  1490.   local nextLine = inputFile.readLine()
  1491.   if (nextLine ~= nil) then
  1492.     returnVal = tonumber(nextLine)
  1493.   end
  1494.  
  1495.   return returnVal
  1496. end
  1497.  
  1498. -- ********************************************************************************** --
  1499. -- Startup function to support resuming mining turtle
  1500. -- ********************************************************************************** --
  1501. function isResume()
  1502.  
  1503.   local returnVal = false
  1504.  
  1505.   -- Try to open the resume file
  1506.   local resumeFile = fs.open(startupParamsFile, "r")
  1507.   if (resumeFile == nil) then
  1508.     -- No resume file (presume that we are not supporting it)
  1509.     supportResume = false
  1510.   else
  1511.     writeMessage("Found startup params file", messageLevel.DEBUG)
  1512.  
  1513.     -- Read in the startup params
  1514.     quarryWidth = readNumber(resumeFile)
  1515.     startHeight = readNumber(resumeFile)
  1516.     noiseBlocksCount = readNumber(resumeFile)
  1517.     lastEmptySlot = readNumber(resumeFile)
  1518.     resumeFile.close()
  1519.  
  1520.     -- If the parameters were successfully read, then set the resuming flag to true
  1521.     if ((quarryWidth ~= nil) and (startHeight ~= nil) and (noiseBlocksCount ~= nil) and (lastEmptySlot ~= nil)) then
  1522.  
  1523.       resuming = true
  1524.       writeMessage("Read params", messageLevel.DEBUG)
  1525.  
  1526.       -- Determine the look for chest and mining offset
  1527.       if (lastEmptySlot == 14) then
  1528.         lookForChests = true
  1529.         miningOffset = 0
  1530.       else
  1531.         lookForChests = false
  1532.         miningOffset = 1
  1533.       end
  1534.  
  1535.       -- Get the turtle resume location
  1536.       resumeFile = fs.open(oreQuarryLocation, "r")
  1537.       if (resumeFile ~= nil) then
  1538.  
  1539.         resumeMiningState = readNumber(resumeFile)
  1540.         resumeX = readNumber(resumeFile)
  1541.         resumeY = readNumber(resumeFile)
  1542.         resumeZ = readNumber(resumeFile)
  1543.         resumeOrient = readNumber(resumeFile)
  1544.         resumeFile.close()
  1545.  
  1546.         -- Ensure that the resume location has been found
  1547.         if ((resumeMiningState ~= nil) and (resumeX ~= nil) and (resumeY ~= nil) and (resumeZ ~= nil) and (resumeOrient ~= nil)) then
  1548.           returnVal = true
  1549.           local emptiedInventory = false
  1550.  
  1551.           -- Perform any mining state specific startup
  1552.           if (resumeMiningState == miningState.EMPTYINVENTORY) then
  1553.             -- Am mid way through an empty inventory cycle. Complete it before
  1554.             -- starting the main Quarry function
  1555.             returnToStartAndUnload(true)
  1556.             resuming = true
  1557.  
  1558.             -- Continue from the current position
  1559.             resumeX = currX
  1560.             resumeY = currY
  1561.             levelToReturnTo = resumeY
  1562.             resumeZ = currZ
  1563.             resumeOrient = currOrient
  1564.  
  1565.             writeMessage("Resuming with state of "..currMiningState, messageLevel.DEBUG)
  1566.             resumeMiningState = currMiningState
  1567.             emptiedInventory = true
  1568.           end
  1569.  
  1570.           -- If was emptying a chest when the program stopped, then move back
  1571.           -- to a point which the Quarry
  1572.           if (resumeMiningState == miningState.EMPTYCHESTDOWN) then
  1573.  
  1574.             -- Set the current X, Y, Z and orientation to the true position that
  1575.             -- the turtle is at
  1576.             if (emptiedInventory == false) then
  1577.               currX = resumeX
  1578.               currY = resumeY
  1579.               currZ = resumeZ
  1580.               currOrient = resumeOrient
  1581.             end
  1582.  
  1583.             -- Set the mining state as layer, assume haven't been through zero
  1584.             -- zero and set the level to return to as the one below the current one
  1585.             currMiningState = miningState.LAYER
  1586.             levelToReturnTo = currY - 2
  1587.             haveBeenAtZeroZeroOnLayer = false
  1588.  
  1589.             -- Temporarily disable resuming (so that the new location is written to the file
  1590.             -- in case the program stops again)
  1591.             resuming = false
  1592.             turtleUp()
  1593.             resuming = true
  1594.  
  1595.             resumeY = currY
  1596.             resumeMiningState = miningState.LAYER
  1597.           end
  1598.         end
  1599.       end
  1600.     end
  1601.  
  1602.     if (returnVal == false) then
  1603.       writeMessage("Failed to resume", messageLevel.ERROR)
  1604.     end
  1605.   end
  1606.  
  1607.   return returnVal
  1608. end
  1609.  
  1610. -- ********************************************************************************** --
  1611. -- Main Function                                          
  1612. -- ********************************************************************************** --
  1613. -- Process the input arguments - storing them to global variables
  1614. local args = { ... }
  1615. local paramsOK = true
  1616.  
  1617. -- Detect whether this is a wireless turtle, and if so, open the modem
  1618. local peripheralConnected = peripheral.getType("right")
  1619. if (peripheralConnected == "modem") then
  1620.   isWirelessTurtle = true
  1621. end
  1622.  
  1623. -- If a wireless turtle, open the modem
  1624. if (isWirelessTurtle == true) then
  1625.   turtleId = os.getComputerLabel()
  1626.   rednet.open("right")
  1627. end
  1628.  
  1629. if (#args == 0) then
  1630.   -- Is this a resume?
  1631.   if (isResume() == false) then
  1632.     paramsOK = false
  1633.   end
  1634. elseif (#args == 1) then
  1635.   quarryWidth = tonumber(args[1])
  1636.   local x, y, z = gps.locate(5)
  1637.   startHeight = y
  1638.   if (startHeight == nil) then
  1639.     writeMessage("Can't locate GPS", messageLevel.FATAL)
  1640.     paramsOK = false
  1641.   end
  1642. elseif (#args == 2) then
  1643.   if (args[2] == "/r") then
  1644.     quarryWidth = tonumber(args[1])
  1645.     supportResume = false
  1646.   else
  1647.     quarryWidth = tonumber(args[1])
  1648.     startHeight = tonumber(args[2])
  1649.   end
  1650. elseif (#args == 3) then
  1651.   quarryWidth = tonumber(args[1])
  1652.   startHeight = tonumber(args[2])
  1653.   if (args[3] == "/r") then
  1654.     supportResume = false
  1655.   else
  1656.     paramsOK = false
  1657.   end
  1658. end
  1659.  
  1660. if ((paramsOK == false) and (resuming == false)) then
  1661.   writeMessage("Usage: "..shell.getRunningProgram().." <diameter> [turtleY] [/r]", messageLevel.FATAL)
  1662.   paramsOK = false
  1663. end
  1664.  
  1665. if (paramsOK == true) then
  1666.   if ((startHeight < 6) or (startHeight > 128)) then
  1667.     writeMessage("turtleY must be between 6 and 128", messageLevel.FATAL)
  1668.     paramsOK = false
  1669.   end
  1670.  
  1671.   if ((quarryWidth < 2) or (quarryWidth > 64)) then
  1672.     writeMessage("diameter must be between 2 and 64", messageLevel.FATAL)
  1673.     paramsOK = false
  1674.   end
  1675. end
  1676.  
  1677. if (paramsOK == true) then
  1678.   if (resuming == true) then
  1679.     writeMessage("Resuming Ore Quarry...", messageLevel.INFO)
  1680.   else
  1681.     writeMessage("----------------------------------", messageLevel.INFO)
  1682.     writeMessage("** Ore Quarry v0.71 by AustinKK **", messageLevel.INFO)
  1683.     writeMessage("----------------------------------", messageLevel.INFO)
  1684.   end
  1685.  
  1686.   -- Set the turtle's starting position
  1687.   currX = 0
  1688.   currY = startHeight
  1689.   currZ = 0
  1690.   currOrient = direction.FORWARD
  1691.  
  1692.   -- Calculate which blocks in the inventory signify noise blocks
  1693.   if (resuming == false) then
  1694.     determineNoiseBlocksCountCount()
  1695.   end
  1696.  
  1697.   if ((noiseBlocksCount == 0) or (noiseBlocksCount > 13)) then
  1698.     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)
  1699.   else
  1700.     -- If we are supporting resume (and are not currently in the process of resuming)
  1701.     -- then store startup parameters in appropriate files
  1702.     if ((supportResume == true) and (resuming == false)) then
  1703.       -- Write the startup parameters to  file
  1704.       local outputFile = io.open(startupParamsFile, "w")
  1705.       outputFile:write(quarryWidth)
  1706.       outputFile:write("\n")
  1707.       outputFile:write(startHeight)
  1708.       outputFile:write("\n")
  1709.       outputFile:write(noiseBlocksCount)
  1710.       outputFile:write("\n")
  1711.       outputFile:write(lastEmptySlot)
  1712.       outputFile:write("\n")
  1713.       outputFile:close()
  1714.  
  1715.       -- Setup the startup file
  1716.  
  1717.       -- Take a backup of the current startup file
  1718.       if (fs.exists("startup") == true) then
  1719.         fs.copy("startup", startupBackup)
  1720.         outputFile = io.open("startup", "a")
  1721.       else
  1722.         outputFile = io.open("startup", "w")
  1723.       end
  1724.      
  1725.       -- Write an info message so that people know how to get out of auto-resume
  1726.       outputFile:write("\nprint(\"Running auto-restart...\")\n")
  1727.       outputFile:write("print(\"If you want to stop auto-resume and restore original state:\")\n")
  1728.       outputFile:write("print(\"1) Hold Ctrl-T until the program terminates\")\n")
  1729.       outputFile:write("print(\"2) Type \\\"rm startup\\\" (without quotes) and hit Enter\")\n")
  1730.       outputFile:write("print(\"\")\n\n")
  1731.  
  1732.       -- Write the code required to restart the turtle
  1733.       outputFile:write("shell.run(\"")
  1734.       outputFile:write(shell.getRunningProgram())
  1735.       outputFile:write("\")\n")
  1736.       outputFile:close()
  1737.  
  1738.     end
  1739.  
  1740.     -- Create a Quarry
  1741.     turtle.select(1)
  1742.     currentlySelectedSlot = 1
  1743.     createQuarry()
  1744.  
  1745.     -- Restore the file system to its original configuration
  1746.     if (supportResume == true) then
  1747.       fs.delete("startup")
  1748.       if (fs.exists(startupBackup) == true) then
  1749.         fs.move(startupBackup, "startup")
  1750.       end
  1751.  
  1752.       if (fs.exists(startupParamsFile) == true) then
  1753.         fs.delete(startupParamsFile)
  1754.       end
  1755.  
  1756.       if (fs.exists(oreQuarryLocation) == true) then
  1757.         fs.delete(oreQuarryLocation)
  1758.       end
  1759.  
  1760.       if (fs.exists(returnToStartFile) == true) then
  1761.         fs.delete(returnToStartFile)
  1762.       end
  1763.     end
  1764.   end
  1765. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement