daily pastebin goal
67%
SHARE
TWEET

Quarry 3.5.1

civilwargeeky Jun 5th, 2014 383 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[
  2. Version 3.5.1
  3. Recent Changes:
  4.   Fixed Bug with modem in most recent version of CC
  5.   Ore Quarry!!!
  6.   Completely redid the system of dropping items off
  7.   Improved session restoring for those using fuel
  8.   Added New Rednet Support
  9.   New Arguments!
  10.     -oreQuarry [t/f] This will start an oreQuarry :D
  11.     -dumpCompareItems [t/f] If true, the oreQuarry will drop off junk compare items
  12.     -extraDropItems [force] Tells the oreQuarry that you want to have extra drop-off items, like cobblestone
  13.     -atChest [force] Using this with -resume will tell the turtle that it is at its chest, and needs to go back to where it was
  14. ]]
  15. --Defining things
  16. civilTable = nil; _G.civilTable = {}; setmetatable(civilTable, {__index = _G}); setfenv(1,civilTable)
  17. VERSION = "3.5.1" --Adding this so I can differentiate versions on error messages
  18. originalDay = os.day() --Used in logging
  19. numResumed = 0 --Number of times turtle has been resumed
  20. -------Defaults for Arguments----------
  21. --Arguments assignable by text
  22. x,y,z = 3,3,3 --These are just in case tonumber fails
  23. inverted = false --False goes from top down, true goes from bottom up [Default false]
  24. rednetEnabled = false --Default rednet on or off  [Default false]
  25. --Arguments assignable by tArgs
  26. dropSide = "front" --Side it will eject to when full or done [Default "front"]
  27. careAboutResources = true --Will not stop mining once inventory full if false [Default true]
  28. doCheckFuel = true --Perform fuel check [Default true]
  29. doRefuel = false --Whenever it comes to start location will attempt to refuel from inventory [Default false]
  30. invCheckFreq = 5 --Will check for inventory full every <-- moved spaces [Default 10]
  31. keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1]
  32. fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate]
  33. saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"]
  34. doBackup = true --If it will keep backups for session persistence [Default true]
  35. uniqueExtras = 8 --How many different items (besides cobble) the turtle expects. [Default 8]
  36. maxTries = 50 --How many times turtle will try to dig a block before it "counts" bedrock [Default 50]
  37. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  38. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  39. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  40. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  41. logExtension = "" --The extension of the file (e.g. ".txt") [Default ""]
  42. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  43. enderChestEnabled = false --Whether or not to use an ender chest [Default false]
  44. enderChestSlot = 16 --What slot to put the ender chest in [Default 16]
  45. oreQuarry = false --Enables ore quarry functionailty [Default false]
  46. dumpCompareItems = true --If ore quarry, the turtle will dump items compared to (like cobblestone) [Default true]
  47. --Standard number slots for fuel (you shouldn't care)
  48. fuelTable = { --Will add in this amount of fuel to requirement.
  49. safe = 1000,
  50. moderate = 200,
  51. loose = 0 } --Default 1000, 200, 0
  52. --Standard rednet channels
  53. channels = {
  54. send = os.getComputerID() + 1  ,
  55. receive = os.getComputerID() + 101 ,
  56. confirm = "Turtle Quarry Receiver",
  57. message = "Civil's Quarry",
  58. }
  59.  
  60. --AVERAGE USER: YOU DON'T CARE BELOW THIS POINT
  61.  
  62. local help_paragraph = [[
  63. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  64. -Default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  65. -dim: [length] [width] [height] This sets the dimensions for the quarry
  66. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  67. -rednet: [t/f] If true and you have a wireless modem on the turtle, will attempt to make a rednet connection for sending important information to a screen
  68. -restore / -resume: If your quarry stopped in the middle of its run, use this to resume at the point where the turtle was. Not guarenteed to work properly. For more accurate location finding, check out the -GPS parameter
  69. -oreQuarry: [t/f] If true, the turtle will use ore quarry mode. It will not mine the blocks that are placed in the turtle initially. So if you put in stone, it will ignore stone blocks and only mine ores.
  70. -atChest: [force] This is for use with "-restore," this will tell the restarting turtle that it is at its home chest, so that if it had gotten lost, it now knows where it is.
  71. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  72. -doCheckFuel: [t/f] If you for some reason don't want the program to check fuel usage, set to false. This is honestly a hold-over from when the refueling algorithm was awful...
  73. -uniqueExtras: [number] The expected number of slots filled with low-stacking items like ore. Higher numbers request more fuel.
  74. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  75. -enderChest: This one is special. If you use "-enderChest true" then it will use an enderChest in the default slot. However, you can also do "-enderChest [slot]" then it will take the ender chest from whatever slot you tell it to. Like 7... or 14... or whatever.
  76. -GPS: [force] If you use "-GPS" and there is a GPS network, then the turtle will record its first two positions to precisly calculate its position if it has to restart. This will only take two GPS readings
  77. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  78. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  79. -startY: [current Y coord] Randomly encountering bedrock? This is the parameter for you! Just give it what y coordinate you are at right now. If it is not within bedrock range, it will never say it found bedrock
  80. -extraDropItems: [force] If oreQuarry then this will prompt the user for extra items to drop, but not compare to (like cobblestone)
  81. -dumpCompareItems: [t/f] If oreQuarry and this is true, the turtle will dump off compare blocks instead of storing them in a chest
  82. -maxTries: [number] This is the number of times the turtle will try to dig before deciding its run into bedrock.
  83. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  84. -doBackup: [t/f] If false, will not back up important information and cannot restore, but will not make an annoying file (Actually I don't really know why anyone would use this...)
  85. -saveFile: [word] This is what the backup file will be called
  86. -logFolder: [word] The folder that quarry logs will be stored in
  87. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  88. -invCheckFreq: [number] This is how often the turtle will check if it has the proper amount of slots open
  89. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every invCheckFreq blocks
  90. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  91. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  92.   =
  93.   C _ |
  94.       |
  95.       |
  96.       |
  97.       |_ _ _ _ >
  98. -manualPos: [xPos] [zPos] [yPos] [facing] This is for advanced use. If the server reset when the turtle was in the middle of a 100x100x100 quarry, fear not, you can now manually set the position of the turtle. yPos is always positive. The turtle's starting position is 0, 1, 1, 0. Facing is measured 0 - 3. 0 is forward, and it progresses clockwise. Example- "-manualPos 65 30 30 2"
  99. -help: Thats what this is :D
  100. Examples: Everything below is examples and tips for use
  101. Important Note:
  102.   None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  103. Examples [1]:
  104.   Want to just start a quarry from the interface, without going through menus? It's easy! Just use some parameters. Assume you called the program "quarry." To start a 10x6x3 quarry, you just type in "quarry -dim 10 6 3 -default".
  105.   You just told it to start a quarry with dimensions 10x6x3, and "-default" means it won't prompt you about invert or rednet. Wasn't that easy?
  106. Examples [2]:
  107.   Okay, so you've got the basics of this now, so if you want, you can type in really long strings of stuff to make the quarry do exactly what you want. Now, say you want a 40x20x9, but you want it to go down to diamond level, and you're on the surface (at y = 64). You also want it to send rednet messages to your computer so you can see how its doing.
  108. Examples [2] [cont.]:
  109.   Oh yeah! You also want it to use an ender chest in slot 12 and restart if the server crashes. Yeah, you can do that. You would type
  110.   "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  111.   BAM. Now you can just let that turtle do it's thing
  112. Tips:
  113.   The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  114.  
  115.   Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  116. Tips [cont.]:
  117.   For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  118.  
  119.   For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  120. Tips [cont.]:
  121.   If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  122.  
  123.   If you want, you can load this program onto a computer, and use "quarry -help" so you can have help with the parameters whenever you want.
  124. Internal Config:
  125.   At the top of this program is an internal configuration file. If there is some setup that you use all the time, you can just change the config value at the top and run "quarry -default" for a quick setup.
  126.  
  127.   You can also use this if there are settings that you don't like the default value of.
  128. ]]
  129.  
  130. --Parsing help for display
  131. --[[The way the help table works:
  132. All help indexes are numbered. There is a help[i].title that contains the title,
  133. and the other lines are in help[i][1] - help[i][#help[i] ]
  134. Different lines (e.g. other than first) start with a space.
  135. As of now, the words are not wrapped, fix that later]]
  136. local help = {}
  137. local i = 0
  138. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  139. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  140. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  141. local current = string.sub(a,1,-2).."" --Concatenate Trick
  142. if string.sub(current,1,1) ~= " " then
  143. i = i + 1
  144. help[i] = {}
  145. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  146. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  147. elseif string.sub(current,1,1) == " " then
  148. table.insert(help[i], string.sub(current,2, -1).."")
  149. end
  150. end
  151.  
  152.  
  153. local supportsRednet
  154. if peripheral.find then
  155.   supportsRednet = peripheral.find("modem")
  156. else
  157.   supportsRednet = peripheral.getType("right") == "modem"
  158. end
  159.  
  160. local tArgs = {...}
  161. --Pre-defining variables
  162.       xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, startY, chestFull, gotoDest, atChest, fuelLevel, numDropOffs, allowedItems, compareSlots, dumpSlots, selectedSlot, extraDropItems
  163.     = 0,   1,   1,   0,     0,      0,    0,    1,       true   ,  false,     true,     1,          0,        0,      false,     "",       false,   0,         0,           {},             {},           {},      1,            false
  164.    
  165. for i=1, 16 do --Initializing various inventory management tables
  166.   allowedItems[i] = 0 --Number of items allowed in slot when dropping items
  167.   dumpSlots[i] = false --Does this slot contain junk items?
  168. end --compareSlots is a table of the compare slots, not all slots with a condition
  169. totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function), this goes up here because many functions use it
  170.  
  171. function resetDumpSlots()
  172.     for i=1, 16 do
  173.       if oreQuarry then
  174.         if turtle.getItemCount(i) > 0 and i~= enderChestSlot then
  175.           dumpSlots[i] = true
  176.         else
  177.           dumpSlots[i] = false
  178.         end
  179.       else
  180.         dumpSlots[i] = false
  181.       end
  182.     end
  183.     if not oreQuarry and enderChestSlot == 1 then
  184.       dumpSlots[2] = true
  185.     elseif not oreQuarry then
  186.       dumpSlots[1] = true
  187.     end
  188. end
  189.        
  190.  
  191. local function copyTable(tab) local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end --This goes up here because it is a basic utility
  192.  
  193. --NOTE: rowCheck is a bit. true = "right", false = "left"
  194.    
  195. local foundBedrock = false
  196.  
  197. local getFuel, checkFuel
  198. if turtle then
  199.   getFuel = turtle.getFuelLevel  --This is for cleanup at the end
  200.   do --Common variable name...
  201.   local flag = turtle.getFuelLevel() == "unlimited"--Unlimited screws up my calculations
  202.   if flag then --Fuel is disabled
  203.     turtle.getFuelLevel = function() return math.huge end --Infinite Fuel
  204.   end --There is no "else" because it will already return the regular getFuel
  205.   end
  206.   checkFuel = turtle.getFuelLevel --Just an alias for backwards compat
  207.  
  208.   turtle.select(1) --To ensure this is correct
  209. end
  210.  
  211. function select(slot)
  212.   if slot ~= selectedSlot then
  213.     selectedSlot = slot
  214.     return turtle.select(slot), selectedSlot
  215.   end
  216. end
  217.  
  218.  
  219.  -----------------------------------------------------------------
  220. --Input Phase
  221. local function screen(xPos,yPos)
  222. xPos, yPos = xPos or 1, yPos or 1
  223. term.setCursorPos(xPos,yPos); term.clear(); end
  224. local function screenLine(xPos,yPos)
  225. term.setCursorPos(xPos,yPos); term.clearLine(); end
  226.  
  227. screen(1,1)
  228. print("----- Welcome to Quarry! -----")
  229. print("")
  230.  
  231. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  232. local changedT, tArgsWithUpper = {}, {}
  233. changedT.new = function(key, value) table.insert(changedT,{key, value}) end --Numeric list of lists
  234. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  235. for i=1, #tArgs do tArgsWithUpper[i] = tArgs[i]; tArgsWithUpper[tArgsWithUpper[i]] = i; tArgs[i] = tArgs[i]:lower(); tArgs[tArgs[i]] = i end --My signature key-value pair system, now with upper
  236.  
  237. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  238. function addParam(name, displayText, formatString, forcePrompt, trigger, variableOverride) --To anyone that doesn't understand this very well, probably not your best idea to go in here.
  239.   if trigger == nil then trigger = true end --Defaults to being able to run
  240.   if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  241.   if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these
  242.   local toGetText = name:lower() --Because all params are now lowered
  243.   local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  244.   local args = formatString:sub(({formatString:find(formatType)})[2] + 2).."" --Everything in formatString but the type and space
  245.   local variable = variableOverride or name --Goes first to the override for name
  246.   local func = loadstring("return "..variable)
  247.   setfenv(func,getfenv(1))
  248.   local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  249.   if originalValue == nil then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  250.   local givenValue, toRet --Initializing for use
  251.   if tArgs["-"..toGetText] then
  252.     givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  253.   elseif forcePrompt then
  254.     write(displayText.."? ")
  255.     givenValue = io.read()
  256.   end
  257.   if formatType == "force" then --This is the one exception. Should return true if givenValue is nothing
  258.     toRet = (tArgs["-"..toGetText] and true) or false --Will return true if param exists, otherwise false
  259.   end
  260.   if not (givenValue or toRet) then return end --Don't do anything if you aren't given anything. Leave it as default, except for "force"
  261.   if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  262.     toRet = givenValue:sub(1,1):lower() == "y" or givenValue:sub(1,1):lower() == "t" --Accepts true or yes
  263.     if formatString == "boolean special" then
  264.       toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  265.     end
  266.   elseif formatType == "string" then
  267.     toRet = givenValue:match("^[%w%.]+") --Basically anything not a space or control character etc
  268.   elseif formatType == "number" then
  269.     toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  270.     if not toRet then return end --We need a number... Otherwise compare errors
  271.     toRet = math.abs(math.floor(toRet)) --Get proper integers
  272.     local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  273.     startNum, endNum = tonumber(startNum), tonumber(endNum)
  274.     if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  275.   elseif formatType == "side" then
  276.     local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  277.     for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  278.     if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  279.   elseif formatType == "list" then
  280.     toRet = {}
  281.     for a in args:gmatch("[^,]") do
  282.       table.insert(toRet,a)
  283.     end
  284.   elseif formatType == "force" then --Do nothing, everything is already done
  285.   else error("Improper formatType",2)
  286.   end
  287.   if toRet == nil then return end --Don't want to set variables to nil... That's bad
  288.   tempParam = toRet --This is what loadstring will see :D
  289.   local func = loadstring(variable.." = tempParam")
  290.   setfenv(func, getfenv(1))
  291.   func()
  292.   tempParam = nil --Cleanup of global
  293.   if toRet ~= originalValue and displayText ~= "" then
  294.     changedT.new(displayText, tostring(toRet))
  295.   end
  296.   return toRet
  297. end
  298.  
  299. --Check if it is a turtle
  300. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then --If all of these are false then
  301.   print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  302.   print("Press 'q' to quit, or any other key to start help ")
  303.   if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  304. end
  305.  
  306. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  307.   print("You have selected help, press any key to continue"); print("Use arrow keys to naviate, q to quit"); os.pullEvent("key")
  308.   local pos = 1
  309.   local key = 0
  310.   while pos <= #help and key ~= keys.q do
  311.     if pos < 1 then pos = 1 end
  312.     screen(1,1)
  313.     print(help[pos].title)
  314.     for a=1, #help[pos] do print(help[pos][a]) end
  315.     repeat
  316.       _, key = os.pullEvent("key")
  317.     until key == 200 or key == 208 or key == keys.q
  318.     if key == 200 then pos = pos - 1 end
  319.     if key == 208 then pos = pos + 1 end
  320.   end
  321.   error("",0)
  322. end
  323.  
  324. --Saving
  325. addParam("doBackup", "Backup Save File", "boolean")
  326. addParam("saveFile", "Save File Name", "string")
  327.  
  328. restoreFound = fs.exists(saveFile)
  329. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound
  330. if restoreFoundSwitch then
  331.   local file = fs.open(saveFile,"r")
  332.   local test = file.readAll() ~= ""
  333.   file.close()
  334.   if test then
  335.     os.run(getfenv(1),saveFile) --This is where the actual magic happens
  336.     numResumed = numResumed + 1
  337.     if turtle.getFuelLevel() ~= math.huge then --If turtle uses fuel
  338.       if fuelLevel - turtle.getFuelLevel() == 1 then
  339.         if facing == 0 then xPos = xPos + 1
  340.         elseif facing == 2 then xPos = xPos - 1
  341.         elseif facing == 1 then zPos = zPos + 1
  342.         elseif facing == 3 then zPos = zPos - 1 end
  343.       elseif fuelLevel - turtle.getFuelLevel() ~= 0 then
  344.         print("Very Strange Fuel in Restore Section...")
  345.         print("Current: ",turtle.getFuelLevel())
  346.         print("Saved: ",fuelLevel)
  347.         print("Difference: ",fuelLevel - turtle.getFuelLevel())
  348.         os.pullEvent("char")
  349.       end
  350.      end
  351.     if gpsEnabled then --If it had saved gps coordinates
  352.       print("Found GPS Start Coordinates")
  353.       local currLoc = {gps.locate(gpsTimeout)} or {}
  354.       local backupPos = {xPos, yPos, zPos} --This is for comparing to later
  355.       if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  356.         print("GPS Position Successfully Read")
  357.         if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  358.           xPos, yPos, zPos = 0,1,1
  359.           if facing ~= 0 then turnTo(0) end
  360.           print("Is at start")
  361.         else
  362.           if inverted then --yPos setting
  363.           ------------------------------------------------FIX THIS
  364.           end
  365.           local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  366.           if b[3] - a[3] == -1 then--If went north (-Z)
  367.             a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  368.             xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  369.           elseif b[1] - a[1] == 1 then--If went east (+X)
  370.             a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  371.             xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  372.           elseif b[3] - a[3] == 1 then--If went south (+Z)
  373.             a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  374.             xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  375.           elseif b[1] - a[1] == -1 then--If went west (-X)
  376.             a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  377.             xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  378.           else
  379.             print("Improper Coordinates")
  380.             print("GPS Locate Failed, Using Standard Methods")        ----Maybe clean this up a bit to use flags instead.
  381.           end  
  382.         end
  383.         print("X Pos: ",xPos)
  384.         print("Y Pos: ",yPos)
  385.         print("Z Pos: ",zPos)
  386.         print("Facing: ",facing)
  387.         for i=1, 3, 2 do --We want 1 and 3, but 2 could be coming back to start.
  388.           if backupPos[i] ~= currLoc[i] then
  389.             events = {} --We want to remove event queue if not in proper place, so won't turn at end of row or things.
  390.           end
  391.         end
  392.       else
  393.         print("GPS Locate Failed, Using Standard Methods")
  394.       end    
  395.     print("Restore File read successfully. Starting in 3"); sleep(3)
  396.     end
  397.   else
  398.     fs.delete(saveFile)
  399.     print("Restore file was empty, sorry, aborting")
  400.     error("",0)
  401.   end
  402. else --If turtle is just starting
  403.   events = {} --This is the event queue :D
  404.   originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  405. end
  406.  
  407. --Dimensions
  408. if tArgs["-dim"] then
  409.   local a,b,c = x,y,z
  410.   local num = tArgs["-dim"]
  411.   x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  412.   if a ~= x then changedT.new("Length", x) end
  413.   if c ~= z then changedT.new("Width", z) end
  414.   if b ~= y then changedT.new("Height", y) end
  415. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  416.   print("What dimensions?")
  417.   print("")
  418.   --This will protect from negatives, letters, and decimals
  419.   term.write("Length? ")
  420.   x = math.floor(math.abs(tonumber(io.read()) or x))
  421.   term.write("Width? ")
  422.   z = math.floor(math.abs(tonumber(io.read()) or z))
  423.   term.write("Height? ")
  424.   y = math.floor(math.abs(tonumber(io.read()) or y))
  425.   changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  426. end
  427. --Params: parameter/variable name, display name, type, force prompt, boolean condition, variable name override
  428. --Invert
  429. addParam("invert", "Inverted","boolean", true, nil, "inverted")
  430. addParam("startDown","Start Down","number 1-256")
  431. --Inventory
  432. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  433. addParam("enderChest","Ender Chest Enabled","boolean special", nil, nil, "enderChestEnabled") --This will accept anything (including numbers) thats not "f" or "n"
  434. addParam("enderChest", "Ender Chest Slot", "number 1-16", nil, nil, "enderChestSlot") --This will get the number slot if given
  435. if not enderChestEnabled then enderChestSlot = 0 end --This makes everything better
  436. --Rednet
  437. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
  438. addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  439. if gpsEnabled and not restoreFoundSwitch then
  440.   gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  441.   gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  442. end
  443. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  444. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  445. --Fuel
  446. addParam("uniqueExtras","Unique Items", "number 0-15")
  447. addParam("doRefuel", "Refuel from Inventory","boolean", nil, turtle.getFuelLevel() ~= math.huge) --math.huge due to my changes
  448. addParam("doCheckFuel", "Check Fuel", "boolean", nil, turtle.getFuelLevel() ~= math.huge)
  449. --Logging
  450. addParam("logging", "Logging", "boolean")
  451. addParam("logFolder", "Log Folder", "string")
  452. addParam("logExtension","Log Extension", "string")
  453. --Misc
  454. addParam("startY", "Start Y","number 1-256")
  455. addParam("invCheckFreq","Inventory Check Frequency","number 1-342")
  456. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  457. addParam("careAboutResources", "Care About Resources","boolean")
  458. addParam("maxTries","Tries Before Bedrock", "number 1-9001")
  459. --Ore Quarry
  460. addParam("oreQuarry", "Ore Quarry", "boolean" )
  461. addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oreQuarry) --Do not dump compare items if not oreQuarry
  462. addParam("extraDropItems", "", "force", nil, oreQuarry) --Prompt for extra dropItems
  463. addParam("extraDumpItems", "", "force", nil, oreQuarry, "extraDropItems") --changed to Dump
  464.  
  465. --Manual Position
  466. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  467.   local a = tArgs["-manualpos"]
  468.   xPos, zPos, yPos, facing = tonumber(tArgs[a+1]) or xPos, tonumber(tArgs[a+2]) or zPos, tonumber(tArgs[a+3]) or yPos, tonumber(tArgs[a+4]) or facing
  469.   changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  470.   restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  471. end
  472. if addParam("atChest", "Is at Chest", "force") then --This sets position to 0,1,1, facing forward, and queues the turtle to go back to proper row.
  473.   local neededLayer = math.floor((yPos+1)/3)*3-1 --Make it a proper layer, +- because mining rows are 2, 5, etc.
  474.   if neededLayer > 2 and neededLayer%3 ~= 2 then --If turtle was not on a proper mining layer
  475.     print("Last known pos was not in proper layer, restarting quarry")
  476.     sleep(4)
  477.     neededLayer = 2
  478.   end
  479.   xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
  480.   events = {{"goto",1,1,neededLayer, 0}}
  481. end
  482.  
  483.  
  484. local function saveProgress(extras) --Session persistence
  485. exclusions = { modem = true, }
  486. if doBackup then
  487. local toWrite = ""
  488. for a,b in pairs(getfenv(1)) do
  489.   if not exclusions[a] then
  490.       --print(a ,"   ", b, "   ", type(b)) --Debug
  491.     if type(b) == "string" then b = "\""..b.."\"" end
  492.     if type(b) == "table" then b = textutils.serialize(b) end
  493.     if type(b) ~= "function" then
  494.       toWrite = toWrite..a.." = "..tostring(b).."\n"
  495.     end
  496.   end
  497. end
  498. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnesesary
  499. local file
  500. repeat
  501.   file = fs.open(saveFile,"w")
  502. until file --WHY DOES IT SAY ATTEMPT TO INDEX NIL!!!
  503. file.write(toWrite)
  504. if type(extras) == "table" then
  505.   for a, b in pairs(extras) do
  506.     file.write(a.." = "..tostring(b))
  507.   end
  508. end
  509. if turtle.getFuelLevel() ~= math.huge then --Used for location comparing
  510.   file.write("fuelLevel = "..tostring(turtle.getFuelLevel()))
  511. end
  512. file.close()
  513. end
  514. end
  515.  
  516. local area = x*z
  517. local volume = x*y*z
  518. local lastHeight = y%3
  519. layers = math.ceil(y/3)
  520. local yMult = layers --This is basically a smart y/3 for movement
  521. local moveVolume = (area * yMult) --Kept for display percent
  522. --Calculating Needed Fuel--
  523. do --Because many local variables unneeded elsewhere
  524.   local numItems = uniqueExtras --Convenience
  525.   local itemSize = extrasStackSize
  526.   local changeYFuel = 2*(y + startDown)
  527.   local dropOffSupplies = 2*(x + z + y + startDown) --Assumes turtle as far away as possible, and coming back
  528.   local frequency = math.floor(((volume/(64*(16-numItems))) ) --This is complicated: volume / inventory space of turtle, defined as (16-num unique stacks)
  529.                                  * (layers/y)) --This is the ratio of height to actual height mined. Close to 1/3 usually, so divide above by 3
  530.   if enderChestEnabled then frequency = 0 end
  531.   neededFuel = moveVolume + changeYFuel + frequency * dropOffSupplies
  532. end
  533.  
  534. --Getting Fuel
  535. local hasRefueled --This is for oreQuarry prompting
  536. if doCheckFuel and checkFuel() < neededFuel then
  537.   hasRefueled = true
  538.   neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  539.   print("Not enough fuel")
  540.   print("Current: ",checkFuel()," Needed: ",neededFuel)
  541.   print("Starting SmartFuel...")
  542.   sleep(2) --So they can read everything.
  543.   term.clear()
  544.   local oneFuel, neededFuelItems
  545.   local currSlot = 0
  546.   local function output(text, x, y) --For displaying fuel
  547.     local currX, currY = term.getCursorPos()
  548.     term.setCursorPos(x,y)
  549.     term.clearLine()
  550.     term.write(text)
  551.     term.setCursorPos(currX,currY)
  552.     end
  553.   local function roundTo(num, target) --For stacks of fuel
  554.     if num >= target then return target elseif num < 0 then return 0 else return num end
  555.   end
  556.   local function updateScreen()
  557.     output("Welcome to SmartFuel! Now Refueling...", 1,1)
  558.     output("Currently taking fuel from slot "..currSlot,1,2)
  559.     output("Current single fuel: "..tostring(oneFuel or 0),1,3)
  560.     output("Current estimate of needed fuel: ",1,4)
  561.     output("Single Items: "..math.ceil(neededFuelItems or 0),4,5)
  562.     output("Stacks:       "..math.ceil((neededFuelItems or 0) / 64),4,6)
  563.     output("Needed Fuel: "..tostring(neededFuel),1,12)
  564.     output("Current Fuel: "..tostring(checkFuel()),1,13)
  565.   end
  566.   while checkFuel() <= neededFuel do
  567.     currSlot = currSlot + 1
  568.     select(currSlot)
  569.     updateScreen()
  570.     while turtle.getItemCount(currSlot) == 0 do sleep(1.5) end
  571.     repeat
  572.       local previous = checkFuel()
  573.       turtle.refuel(1)
  574.       oneFuel = checkFuel() - previous
  575.       updateScreen()
  576.     until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  577.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  578.     turtle.refuel(math.ceil(roundTo(neededFuelItems, 64))) --Change because can only think about 64 at once.
  579.     if turtle.getItemCount(roundTo(currSlot + 1, 16)) == 0 then --Resets if no more fuel
  580.       currSlot = 0
  581.     end
  582.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  583.   end
  584. end
  585. --Ender Chest Obtaining
  586. function promptEnderChest()
  587.   while turtle.getItemCount(enderChestSlot) ~= 1 do
  588.     screen(1,1)
  589.     print("You have decided to use an Ender Chest!")
  590.     print("Please place one Ender Chest in slot ",enderChestSlot)
  591.     sleep(1)
  592.   end
  593.   print("Ender Chest in slot ",enderChestSlot, " checks out")
  594. end
  595. if enderChestEnabled then
  596.     if restoreFoundSwitch and turtle.getItemCount(enderChestSlot) == 0 then --If the turtle was stopped while dropping off items.
  597.       select(enderChestSlot)
  598.       turtle.dig()
  599.       select(1)
  600.     end
  601.   promptEnderChest()
  602.   allowedItems[enderChestSlot] = 64
  603.   sleep(2)
  604. end
  605. --Setting which slots are marked as compare slots
  606. if oreQuarry then
  607.   if not restoreFoundSwitch then --We don't want to reset compare blocks every restart
  608.     local counter = 0
  609.     for i=1, 16 do if turtle.getItemCount(i) > 0 and i ~= enderChestSlot then counter = counter+1 end end --If the slot has items, but isn't enderChest slot if it is enabled
  610.  
  611.     screen(1,1)
  612.     print("You have selected an Ore Quarry!")
  613.     if counter == 0 or hasRefueled then --If there are no compare slots, or the turtle has refueled, and probably has fuel in inventory
  614.       print("Please place your compare blocks in the first slots\n")
  615.      
  616.       print("Press Enter when done")
  617.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  618.     else
  619.       print("Registering slots as compare slots")
  620.       sleep(1)
  621.     end
  622.     for i=1, 16 do
  623.       if turtle.getItemCount(i) > 0 then
  624.         if i ~= enderChestSlot then
  625.           table.insert(compareSlots, i) --Compare slots are ones compared to while mining. Conditions are because we Don't want to compare to enderChest
  626.           allowedItems[i] = 1 --Blacklist is for dropping off items. The number is maximum items allowed in slot when dropping off
  627.           dumpSlots[i] = true --We also want to ignore all excess of these items, like dirt
  628.         end
  629.       end
  630.     end
  631.     if extraDropItems then
  632.       screen(1,1)
  633.       print("Put in extra drop items now\n")
  634.       print("Press Enter when done")
  635.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  636.       for i=1,16 do
  637.         if not dumpSlots[i] and turtle.getItemCount(i) > 0 then --I don't want to modify from above, so I check it hasn't been assigned.
  638.           dumpSlots[i] = true
  639.           allowedItems[i] = 1
  640.         end
  641.       end
  642.     end
  643.     --This is could go very wrong if this isn't here
  644.     if #compareSlots >= 16-keepOpen then screen(1,1); error("You have more quarry compare items than keep open slots, the turtle will continuously come back to start. Please fix.",0) end
  645.   end
  646.   local counter = 0
  647.   for a, b in pairs(compareSlots) do if  turtle.getItemCount(b) > 0 then counter = counter + 1 end end
  648.   if counter == 0 then
  649.     screen(1,1)
  650.     print("You have an ore quarry without any compare slots. Continue? y/n")
  651.     if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
  652.   end
  653. else
  654.   dumpCompareItems = false --If not an ore quarry, this should definately be false
  655.   if enderChestSlot == 1 then
  656.     dumpSlots[2] = true
  657.   else
  658.     dumpSlots[1] = true
  659.   end
  660. end
  661.  
  662. --Initial Rednet Handshake
  663. if rednetEnabled then
  664.   screen(1,1)
  665.   print("Rednet is Enabled")
  666.   print("The Channel to open is "..channels.send)
  667.   if peripheral.find then
  668.     modem = peripheral.find("modem")
  669.   else
  670.     modem = peripheral.wrap("right")
  671.   end
  672.   modem.open(channels.receive)
  673.   local i = 0
  674.     repeat
  675.       local id = os.startTimer(3)
  676.       i=i+1
  677.       print("Sending Initial Message "..i)
  678.       modem.transmit(channels.send, channels.receive, channels.message)
  679.       local message
  680.       repeat
  681.         local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  682.         message = locMessage
  683.       until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and message == channels.confirm)
  684.     until message == channels.confirm
  685.   connected = true
  686.   print("Connection Confirmed!")
  687.   sleep(1.5)
  688. end
  689. function biometrics(isAtBedrock)
  690.   if not rednetEnabled then return end --This function won't work if rednet not enabled :P
  691.   local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
  692.     percent = percent, relxPos = relxPos, zPos = zPos, xPos = xPos, yPos = yPos,
  693.     layersDone = layersDone, x = x, z = z, layers = layers,
  694.     openSlots = getNumOpenSlots(), mined = mined, moved = moved,
  695.     chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
  696.     isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
  697.     fuel = turtle.getFuelLevel(), volume = volume,
  698.     }
  699.   modem.transmit(channels.send, channels.receive, textutils.serialize(toSend))
  700.   id = os.startTimer(0.1)
  701.   local event, message
  702.   repeat
  703.     local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  704.     event, message = locEvent, locMessage or ""
  705.   until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive)
  706.   if event == "modem_message" then connected = true else connected = false end
  707.   message = message:lower()
  708.   if message == "stop" then error("Rednet said to stop...",0) end
  709.   if message == "return" then
  710.     endingProcedure()
  711.     error('Rednet said go back to start...',0)
  712.   end
  713.   if message == "drop" then
  714.     dropOff()
  715.   end
  716. end
  717. --Showing changes to settings
  718. screen(1,1)
  719. print("Your selected settings:")
  720. if #changedT == 0 then
  721. print("Completely Default")
  722. else
  723. for i=1, #changedT do
  724. print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  725. end
  726. end
  727. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  728.  
  729.  
  730.  
  731. ----------------------------------------------------------------
  732. --Define ALL THE FUNCTIONS
  733. --Event System Functions
  734. function eventAdd(...)
  735.   return table.insert(events,1, {...}) or true
  736. end
  737. function eventGet(pos)
  738.   return events[tonumber(pos) or #events]
  739. end
  740. function eventPop(pos)
  741.   return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  742. end
  743. function eventRun(value, ...)
  744.   local argsList = {...}
  745.   if type(value) == "string" then
  746.     if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  747.       value = value .. "("
  748.       for a, b in pairs(argsList) do --Appending arguments
  749.         local toAppend
  750.         if type(b) == "table" then toAppend = textutils.serialize(b)
  751.         elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  752.         else toAppend = tostring(b) end
  753.         value = value .. (toAppend or "true") .. ", "
  754.       end
  755.       if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  756.         value = value:sub(1,-3)..""
  757.       end
  758.       value = value .. ")"
  759.     end
  760.     --print(value) --Debug
  761.     local func = loadstring(value)
  762.     setfenv(func, getfenv(1))
  763.     return func()
  764.   end
  765. end
  766. function eventClear(pos)
  767.   if pos then events[pos] = nil else events = {} end
  768. end  
  769. function runAllEvents()
  770.   while #events > 0 do
  771.     local toRun = eventGet()
  772.     --print(toRun[1]) --Debug
  773.     eventRun(unpack(toRun))
  774.     eventPop()
  775.   end
  776. end
  777.  
  778. --Display Related Functions
  779. function display() --This is just the last screen that displays at the end
  780.   screen(1,1)
  781.   print("Total Blocks Mined: "..mined)
  782.   print("Current Fuel Level: "..turtle.getFuelLevel())
  783.   print("Cobble: "..totals.cobble)
  784.   print("Usable Fuel: "..totals.fuel)
  785.   print("Other: "..totals.other)
  786.   if rednetEnabled then
  787.     print("")
  788.     print("Sent Stop Message")
  789.     local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
  790.         other = totals.other, fuel = checkFuel() }
  791.     modem.transmit(channels.send,channels.receive,"stop")
  792.     sleep(0.5)
  793.     modem.transmit(channels.send,channels.receive,textutils.serialize(finalTable))
  794.     modem.close(channels.receive)
  795.   end
  796.   if doBackup then fs.delete(saveFile) end
  797. end
  798. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  799. screen(1,1)
  800. print("Blocks Mined")
  801. print(mined)
  802. print("Percent Complete")
  803. print(percent.."%")
  804. print("Fuel")
  805. print(checkFuel())
  806.   -- screen(1,1)
  807.   -- print("Xpos: ")
  808.   -- print(xPos)
  809.   -- print("RelXPos: ")
  810.   -- print(relxPos)
  811.   -- print("Z Pos: ")
  812.   -- print(zPos)
  813.   -- print("Y pos: ")
  814.   -- print(yPos)
  815. if rednetEnabled then
  816. screenLine(1,7)
  817. print("Connected: "..tostring(connected))
  818. end
  819. end
  820. --Utility functions
  821. function logMiningRun(textExtension, extras) --Logging mining runs
  822.   if not logging then return end
  823.   local number, name = 0
  824.   if not fs.isDir(logFolder) then
  825.     fs.delete(logFolder)
  826.     fs.makeDir(logFolder)
  827.   end
  828.   repeat
  829.     number = number + 1 --Number will be at least 2
  830.     name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
  831.   until not fs.exists(name)
  832.   local handle = fs.open(name,"w")
  833.   local function write(...)
  834.     for a, b in ipairs({...}) do
  835.       handle.write(tostring(b))
  836.     end
  837.     handle.write("\n")
  838.   end
  839.   local function boolToText(bool) if bool then return "Yes" else return "No" end end
  840.   write("Welcome to the Quarry Logs!")
  841.   write("Entry Number: ",number)
  842.   write("Quarry Version: ",VERSION)
  843.   write("Dimensions (X Z Y): ",x," ",z," ", y)
  844.   write("Blocks Mined: ", mined)
  845.   write("  Cobble: ", totals.cobble)
  846.   write("  Usable Fuel: ", totals.fuel)
  847.   write("  Other: ",totals.other)
  848.   write("Total Fuel Used: ",  (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  849.   write("Expected Fuel Use: ", neededFuel)
  850.   write("Days to complete mining run: ",os.day()-originalDay)
  851.   write("Day Started: ", originalDay)
  852.   write("Number of times resumed: ", numResumed)
  853.   write("Was an ore quarry? ",boolToText(oreQuarry))
  854.   write("Was inverted? ",boolToText(invert))
  855.   write("Was using rednet? ",boolToText(rednetEnabled))
  856.   write("Chest was on the ",dropSide," side")
  857.   if startDown > 0 then write("Started ",startDown," blocks down") end
  858.   handle.close()
  859. end
  860. --Inventory related functions
  861. function isFull(slots) --Checks if there are more than "slots" used inventory slots.
  862.   slots = slots or 16
  863.   local numUsed = 0
  864.   sleep(0)
  865.   for i=1, 16 do
  866.     if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  867.   end
  868.   if numUsed > slots then
  869.     return true
  870.   end
  871.   return false
  872. end
  873. function countUsedSlots() --Returns number of slots with items in them, as well as a table of item counts
  874.   local toRet, toRetTab = 0, {}
  875.   for i=1, 16 do
  876.     local a = turtle.getItemCount(i)
  877.     if a > 0 then toRet = toRet + 1 end
  878.     table.insert(toRetTab, a)
  879.   end
  880.   return toRet, toRetTab
  881. end
  882. function getSlotsTable() --Just get the table from above
  883.   local _, toRet = countUsedSlots()
  884.   return toRet
  885. end
  886. function getChangedSlots(tab1, tab2) --Returns a table of changed slots. Format is {slotNumber, numberChanged}
  887.   local toRet = {}
  888.   for i=1, min(#tab1, #tab2) do
  889.     diff = math.abs(tab2[i]-tab1[i])
  890.     if diff > 0 then
  891.       table.insert(toRet, {i, diff})
  892.     end
  893.   end
  894.   return toRet
  895. end
  896. function getFirstChanged(tab1, tab2) --Just a wrapper. Probably not needed
  897.   local a = getChangedSlots(tab1,tab2)
  898.   return a[1][1]
  899. end
  900.  
  901. function getRep(which, list) --Gets a representative slot of a type. Expectation is a sequential table of types
  902.   for a,b in pairs(list) do
  903.     if b == which then return a end
  904.   end
  905.   return false
  906. end
  907. function assignTypes(types, count) --The parameters allow a preexisting table to be used, like a table from the origianl compareSlots...
  908.   types, count = types or {1}, count or 1 --Table of types and current highest type
  909.   for i=1, 16 do
  910.     if turtle.getItemCount(i) > 0 then
  911.       select(i)
  912.       for k=1, count do
  913.         if turtle.compareTo(getRep(k, types)) then types[i] = k end
  914.       end
  915.       if not types[i] then
  916.         count = count + 1
  917.         types[i] = count
  918.       end
  919.      
  920.     end
  921.   end
  922.   select(1)
  923.   return types, count
  924. end
  925. function getTableOfType(which, list) --Returns a table of all the slots of which type
  926.   local toRet = {}
  927.   for a, b in pairs(list) do
  928.     if b == which then
  929.       table.insert(toRet, a)
  930.     end
  931.   end
  932.   return toRet
  933. end
  934.  
  935. --This is so the turtle will properly get types, otherwise getRep of a type might not be a dumpSlot, even though it should be.
  936. if not restoreFoundSwitch then --We only want this to happen once
  937.   if oreQuarry then --If its not ore quarry, this screws up type assigning
  938.     initialTypes, initialCount = assignTypes()
  939.   else
  940.     initialTypes, initialCount = {1}, 1
  941.   end
  942. end
  943.  
  944. function count(add) --Done any time inventory dropped and at end, param is add or subtract
  945.   local mod = -1
  946.   if add then mod = 1 end
  947.   slot = {}        --1: Filler 2: Fuel 3:Other --[1] is type, [2] is number
  948.   for i=1, 16 do  
  949.     slot[i] = {}
  950.     slot[i][2] = turtle.getItemCount(i)
  951.   end
  952.  
  953.   local function iterate(toSet , rawTypes, set)
  954.     for _, a in pairs(getTableOfType(toSet, rawTypes)) do --Get all slots matching type
  955.       slot[a][1] = set --Set official type to "set"
  956.     end
  957.   end
  958.  
  959.   --This assigns "dumb" types to all slots based on comparing, then based on knowledge of dump type slots, changes all slots matching a dump type to one. Otherwise, if the slot contains fuel, it is 2, else 3
  960.   local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount) --This gets increasingly numbered types, copyTable because assignTypes will modify it
  961.  
  962.   for i=1, numTypes do
  963.     if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then --Selects the rep slot, checks if it is fuel
  964.       iterate(i, rawTypes, 2) --This type is fuel
  965.     elseif dumpSlots[getRep(i,initialTypes)] then --If the rep of this slot is a dump item. This is intitial types so that the rep is in dump slots
  966.       iterate(i, rawTypes, 1) --This type is cobble/filler
  967.     else
  968.       iterate(i, rawTypes, 3) --This type is other
  969.     end
  970.   end
  971.    
  972.     for i=1,16 do
  973.       if i == enderChestSlot then --Do nothing!
  974.       elseif slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
  975.       elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
  976.       elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
  977.     end
  978.  
  979.   select(1)
  980. end
  981.  
  982. --Mining functions
  983. function dig(doAdd, func)
  984.   if doAdd == nil then doAdd = true end
  985.   func = func or turtle.dig
  986.   if func() then
  987.     if doAdd then
  988.       mined = mined + 1
  989.     end
  990.     return true
  991.   end
  992.   return false
  993. end
  994.  
  995.  
  996.  
  997. function digUp(doAdd)--Regular functions :) I switch definitions for optimization (I think)
  998.   return dig(doAdd, turtle.digUp)
  999. end
  1000. function digDown(doAdd)
  1001.   return dig(doAdd, turtle.digDown)
  1002. end
  1003. if inverted then --If inverted, switch the options
  1004.   digUp, digDown = digDown, digUp
  1005. end
  1006.  
  1007. function smartDig(digUp, digDown) --This function is used only in mine when oreQuarry
  1008.   local blockAbove, blockBelow = digUp and turtle.detectUp(), digDown and turtle.detectDown() --These control whether or not the turtle digs
  1009.   local index = 1
  1010.   for i=1, #compareSlots do
  1011.     if not (blockAbove or blockBelow) then break end --We don't want to go selecting if there is nothing to dig
  1012.     index = i --To access out of scope
  1013.     select(compareSlots[i])
  1014.     if blockAbove and turtle.compareUp() then blockAbove = false end
  1015.     if blockBelow and turtle.compareDown() then blockBelow = false end
  1016.   end
  1017.   table.insert(compareSlots, 1, table.remove(compareSlots, index)) --This is so the last selected slot is the first slot checked, saving a turtle.select call
  1018.   if blockAbove then dig(true, turtle.digUp) end
  1019.   if blockBelow then dig(true, turtle.digDown) end
  1020. end
  1021.  
  1022. function setRowCheckFromPos()
  1023.   rowCheck = (zPos % 2 == 1) --It will turn right at odd rows
  1024. end
  1025. function relxCalc()
  1026.   if rowCheck then relxPos = xPos else relxPos = (x-xPos)+1 end
  1027. end
  1028. function forward(doAdd)
  1029.   if doAdd == nil then doAdd = true end
  1030.   if turtle.forward() then
  1031.     if doAdd then
  1032.       moved = moved + 1
  1033.     end
  1034.     if facing == 0 then
  1035.       xPos = xPos + 1
  1036.     elseif facing == 1 then
  1037.       zPos = zPos + 1
  1038.     elseif facing == 2 then
  1039.       xPos = xPos - 1
  1040.     elseif facing == 3 then
  1041.       zPos = zPos - 1
  1042.     else
  1043.       error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  1044.     end
  1045.     relxCalc()
  1046.     return true
  1047.   end
  1048.   return false
  1049. end
  1050. function up(sneak)
  1051.   sneak = sneak or 1
  1052.   if inverted and sneak == 1 then
  1053.     down(-1)
  1054.   else
  1055.     while not turtle.up() do --Absolute dig, not relative
  1056.       if not dig(true, turtle.digUp) then
  1057.         attackUp()
  1058.         sleep(0.5)
  1059.       end
  1060.     end
  1061.     yPos = yPos - sneak --Oh! I feel so clever
  1062.   end                   --This works because inverted :)
  1063.   saveProgress()
  1064.   biometrics()
  1065. end
  1066. function down(sneak)
  1067.   sneak = sneak or 1
  1068.   local count = 0
  1069.   if inverted and sneak == 1 then
  1070.     up(-1)
  1071.   else
  1072.     while not turtle.down() do
  1073.       count = count + 1
  1074.       if not dig(true, turtle.digDown) then --This is absolute dig down, not relative
  1075.         attackDown()
  1076.         sleep(0.2)
  1077.       end
  1078.       if count > 20 then bedrock() end
  1079.     end
  1080.     yPos = yPos + sneak
  1081.   end
  1082.   saveProgress()
  1083.   biometrics()
  1084. end
  1085. function right(num)
  1086.   num = num or 1
  1087.   for i=1, num do facing = coterminal(facing+1); saveProgress(); turtle.turnRight() end
  1088. end
  1089. function left(num)
  1090.   num = num or 1
  1091.   for i=1, num do facing = coterminal(facing-1); saveProgress(); turtle.turnLeft() end
  1092. end
  1093. function attack(doAdd, func)
  1094.   doAdd = doAdd or true
  1095.   func = func or turtle.attack
  1096.   if func() then
  1097.     if doAdd then
  1098.       attacked = attacked + 1
  1099.     end
  1100.     return true
  1101.   end
  1102.   return false
  1103. end
  1104. function attackUp(doAdd)
  1105.   if inverted then
  1106.     return attack(doAdd, turtle.attackDown)
  1107.   else
  1108.     return attack(doAdd, turtle.attackUp)
  1109.   end
  1110. end
  1111. function attackDown(doAdd)
  1112.   if inverted then
  1113.     return attack(doAdd, turtle.attackUp)
  1114.   else
  1115.     return attack(doAdd, turtle.attackDown)
  1116.   end
  1117. end
  1118.  
  1119.  
  1120. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  1121.   if doCheckInv == nil then doCheckInv = true end
  1122.   if doDigDown == nil then doDigDown = true end
  1123.   if doDigUp == nil then doDigUp = true end
  1124.   if outOfPath == nil then outOfPath = false end
  1125.   isInPath = (not outOfPath) --For rednet
  1126.   if inverted then
  1127.     doDigUp, doDigDown = doDigDown, doDigUp --Just Switch the two if inverted
  1128.   end
  1129.   if doRefuel and checkFuel() <= fuelTable[fuelSafety]/2 then
  1130.     for i=1, 16 do
  1131.     if turtle.getItemCount(i) > 0 then
  1132.       select(i)
  1133.       if checkFuel() < 200 + fuelTable[fuelSafety] then
  1134.         turtle.refuel()
  1135.       end
  1136.     end
  1137.     end
  1138.     select(1)
  1139.   end
  1140.   local count = 0
  1141.   while not forward(not outOfPath) do
  1142.     sleep(0) --Calls coroutine.yield to prevent errors
  1143.     count = count + 1
  1144.     if not dig() then
  1145.       attack()
  1146.     end
  1147.     if count > 10 then
  1148.       attack()
  1149.       sleep(0.2)
  1150.     end
  1151.     if count > maxTries then
  1152.       if turtle.getFuelLevel() == 0 then --Don't worry about inf fuel because I modified this function
  1153.         saveProgress({doCheckFuel = true})
  1154.         error("No more fuel",0)
  1155.       elseif yPos > (startY-7) and turtle.detect() then --If it is near bedrock
  1156.         bedrock()
  1157.       else --Otherwise just sleep for a bit to avoid sheeps
  1158.         sleep(1)
  1159.       end
  1160.     end
  1161.   end
  1162.   checkSanity() --Not kidding... This is necessary
  1163.   saveProgress(tab)
  1164.   if not oreQuarry then --The digging up and down part
  1165.     if doDigUp then
  1166.       while turtle.detectUp() do
  1167.         sleep(0) --Calls coroutine.yield
  1168.         if not dig(true,turtle.digUp) then --This needs to be an absolute, because we are switching doDigUp/Down
  1169.           if not attackUp() then
  1170.             if yPos > (startY-7) then bedrock() end --Checking for bedrock, but respecting user wishes
  1171.           end
  1172.         end
  1173.       end
  1174.     end
  1175.     if doDigDown then
  1176.      dig(true,turtle.digDown) --This needs to be absolute as well
  1177.     end
  1178.   else
  1179.     smartDig(doDigUp, doDigDown)
  1180.   end
  1181.   percent = math.ceil(moved/moveVolume*100)
  1182.   updateDisplay()
  1183.   if doCheckInv and careAboutResources then
  1184.     if moved%invCheckFreq == 0 then
  1185.      if isFull(16-keepOpen) then dropOff() end
  1186.     end
  1187.   end
  1188.   biometrics()
  1189. end
  1190. --Insanity Checking
  1191. function checkSanity()
  1192.   if not isInPath then --I don't really care if its not in the path.
  1193.     return true
  1194.   end
  1195.   if not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  1196.     turnTo(0)
  1197.     rowCheck = true
  1198.   end
  1199.   if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  1200.     saveProgress()
  1201.     print("I have gone outside boundaries, attempting to fix (maybe)")
  1202.     if xPos > x then goto(x, zPos, yPos, 2) end --I could do this with some fancy math, but this is much easier
  1203.     if xPos < 0 then goto(1, zPos, yPos, 0) end
  1204.     if zPos > z then goto(xPos, z, yPos, 3) end
  1205.     if zPos < 0 then goto(xPos, 1, yPos, 1) end
  1206.     setRowCheckFromPos() --Row check right (maybe left later)
  1207.     relxCalc() --Get relxPos properly
  1208.     eventClear()
  1209.    
  1210.     --[[
  1211.     print("Oops. Detected that quarry was outside of predefined boundaries.")
  1212.     print("Please go to my forum thread and report this with a short description of what happened")
  1213.     print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  1214.     error("",0)]]
  1215.   end
  1216. end
  1217.  
  1218. local function fromBoolean(input) --Like a calculator
  1219. if input then return 1 end
  1220. return 0
  1221. end
  1222. local function multBoolean(first,second) --Boolean multiplication
  1223. return (fromBoolean(first) * fromBoolean(second)) == 1
  1224. end
  1225. function coterminal(num, limit) --I knew this would come in handy :D
  1226. limit = limit or 4 --This is for facing
  1227. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  1228. end
  1229. if tArgs["-manualpos"] then
  1230.   facing = coterminal(facing) --Done to improve support for "-manualPos"
  1231.   if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end --Ditto
  1232.   relxCalc() --Ditto
  1233. end
  1234.  
  1235. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  1236. function turnTo(num)
  1237.   num = num or facing
  1238.   num = coterminal(num) --Prevent errors
  1239.   local turnRight = true
  1240.   if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  1241.   while facing ~= num do          --The above is used to smartly turn
  1242.     if turnRight then
  1243.       right()
  1244.     else
  1245.       left()
  1246.     end
  1247.   end
  1248. end
  1249. function goto(x,z,y, toFace, destination)
  1250.   --Will first go to desired z pos, then x pos, y pos varies
  1251.   x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  1252.   gotoDest = destination or "" --This is used by biometrics
  1253.   --Possible destinations: layerStart, quarryStart
  1254.   if yPos > y then --Will go up first if below position
  1255.     while yPos~=y do up() end
  1256.   end
  1257.   if zPos > z then
  1258.     turnTo(3)
  1259.   elseif zPos < z then
  1260.     turnTo(1)
  1261.   end
  1262.   while zPos ~= z do mine(false,false,true,false) end
  1263.   if xPos > x then
  1264.     turnTo(2)
  1265.   elseif xPos < x then
  1266.     turnTo(0)
  1267.   end
  1268.   while xPos ~= x do mine(false,false,true,false) end
  1269.   if yPos < y then --Will go down after if above position
  1270.     while yPos~=y do down() end
  1271.   end
  1272.   turnTo(toFace)
  1273.   saveProgress()
  1274.   gotoDest = ""
  1275. end
  1276. function getNumOpenSlots()
  1277.   local toRet = 0
  1278.   for i=1, 16 do
  1279.     if turtle.getItemCount(i) == 0 then
  1280.       toRet = toRet + 1
  1281.     end
  1282.   end
  1283.   return toRet
  1284. end
  1285.  
  1286. --[[
  1287. function drop(side, final, allowSkip)
  1288. side = sides[side] or "front"    --The final number means that it will
  1289. if final then final = 0 else final = 1 end --drop a whole stack at the end
  1290. local allowSkip = allowSkip or (final == 0) --This will allow drop(side,t/f, rednetConnected)
  1291. count()
  1292. if doRefuel then
  1293.   for i=1, 16 do
  1294.     if slot[i][1] == 2 then
  1295.       select(i); turtle.refuel()
  1296.     end
  1297.   end
  1298.   select(1)
  1299. end
  1300. if side == "right" then turnTo(1) end
  1301. if side == "left" then turnTo(3) end
  1302. local whereDetect, whereDrop1, whereDropAll
  1303. local _1 = slot[1][2] - final --All but one if final, all if not final
  1304. if side == "top" then
  1305. whereDetect = turtle.detectUp ; whereDrop = turtle.dropUp
  1306. elseif side == "bottom" then
  1307. whereDetect = turtle.detectDown ; whereDrop = turtle.dropDown
  1308. else
  1309. whereDetect = turtle.detect; whereDrop = turtle.drop
  1310. end
  1311. local function waitDrop(val) --This will just drop, but wait if it can't
  1312.   val = val or 64
  1313.   local try = 1
  1314.   while not whereDrop(val) do
  1315.     print("Chest Full, Try "..try)
  1316.     chestFull = true
  1317.     if rednetEnabled then --To send that the chest is full
  1318.       biometrics()
  1319.     end
  1320.     try = try + 1
  1321.     sleep(2)
  1322.   end
  1323.   chestFull = false
  1324. end
  1325. repeat
  1326. local detected = whereDetect()
  1327. if detected then
  1328.   waitDrop(_1)
  1329.   for i=1, 2 do --This is so I quit flipping missing items when chests are partially filled
  1330.     for i=2, 16 do
  1331.       if turtle.getItemCount(i) > 0 then
  1332.         select(i)
  1333.         waitDrop(nil, i)
  1334.       end
  1335.     end
  1336.   end
  1337. elseif not allowSkip then
  1338.   print("Waiting for chest placement place a chest to continue")
  1339.   while not whereDetect() do
  1340.     sleep(1)
  1341.   end
  1342. end
  1343. until detected or allowSkip
  1344. if not allowSkip then totals.cobble = totals.cobble - 1 end
  1345. select(1)
  1346. end
  1347. ]]
  1348.  
  1349. --Ideas: Bring in inventory change-checking functions, count blocks that have been put in, so it will wait until all blocks have been put in.
  1350. local function waitDrop(slot, allowed, whereDrop) --This will just drop, but wait if it can't
  1351.   allowed = allowed or 0
  1352.   while turtle.getItemCount(slot) > allowed do --No more half items stuck in slot!
  1353.     local tries = 1
  1354.     while not whereDrop(turtle.getItemCount(slot)-allowed) do --Drop off only the amount needed
  1355.       screen(1,1)
  1356.       print("Chest Full, Try "..tries)
  1357.       chestFull = true
  1358.       biometrics()--To send that the chest is full
  1359.       tries = tries + 1
  1360.       sleep(2)
  1361.     end
  1362.     chestFull = false
  1363.   end
  1364. end
  1365.  
  1366. function drop(side, final)
  1367.   side = sides[side] or "front"
  1368.   local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
  1369.   if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
  1370.   if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
  1371.   if side == "right" then turnTo(1); dropFacing = 0 end
  1372.   if side == "left" then turnTo(3); dropFacing = 0 end
  1373.   local properFacing = facing --Capture the proper direction to be facing
  1374.  
  1375.   count(true) --Count number of items before drop. True means add. This is before chest detect, because could be final
  1376.  
  1377.   while not detectFunc() do
  1378.     if final then return end --If final, we don't need a chest to be placed, we just won't drop.
  1379.     chestFull = true
  1380.     biometrics() --Let the user know there is a problem with chest
  1381.     screen(1,1) --Clear screen
  1382.     print("Waiting for chest placement on ",side," side (when facing quarry)")
  1383.     sleep(2)
  1384.   end
  1385.   chestFull = false
  1386.  
  1387.   for i=1,16 do
  1388.     --if final then allowedItems[i] = 0 end --0 items allowed in all slots if final ----It is already set to 1, so just remove comment if want change
  1389.     if turtle.getItemCount(i) > 0 then --Saves time, stops bugs
  1390.       if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing) --Turn around to drop junk, not store it. dumpComapareItems is global config
  1391.       else turnTo(properFacing) --Turn back to proper position... or do nothing if already there
  1392.       end
  1393.       select(i)
  1394.       if doRefuel and slot[i][1] == 2 then turtle.refuel(turtle.getItemCount(i)-allowedItems[i]) --Refueling option working
  1395.       else waitDrop(i, allowedItems[i], dropFunc)
  1396.       end
  1397.     end
  1398.   end
  1399.  
  1400.   if oreQuarry then count(false) end--Subtract the items still there if oreQuarry
  1401.   resetDumpSlots() --So that slots gone aren't counted as dump slots next
  1402.  
  1403.   select(1) --For fanciness sake
  1404.  
  1405. end
  1406.  
  1407. function dropOff() --Not local because called in mine()
  1408.   local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  1409.   if careAboutResources then
  1410.     if not enderChestEnabled then --Regularly
  1411.       eventAdd("goto", 1,1,currY,2) --Need this step for "-startDown"
  1412.       eventAdd("goto(0,1,1,2)")
  1413.       eventAdd("drop", dropSide,false)
  1414.       eventAdd("turnTo(0)")
  1415.       eventAdd("mine",false,false,true,false)
  1416.       eventAdd("goto(1,1,1, 0)")
  1417.       eventAdd("goto", 1, 1, currY, 0)
  1418.       eventAdd("goto", currX,currZ,currY,currFacing)
  1419.     else --If using an enderChest
  1420.       if turtle.getItemCount(enderChestSlot) ~= 1 then eventAdd("promptEnderChest()") end
  1421.       eventAdd("turnTo",currFacing-2)
  1422.       eventAdd("dig",false)
  1423.       eventAdd("select",enderChestSlot)
  1424.       eventAdd("turtle.place")
  1425.       eventAdd("drop","front",false)
  1426.       eventAdd("select", enderChestSlot)
  1427.       eventAdd("dig",false)
  1428.       eventAdd("turnTo",currFacing)
  1429.       eventAdd("select(1)")
  1430.     end
  1431.   runAllEvents()
  1432.   numDropOffs = numDropOffs + 1 --Analytics tracking
  1433.   end
  1434. return true
  1435. end
  1436. function endingProcedure() --Used both at the end and in "biometrics"
  1437.   eventAdd("goto",1,1,yPos,2,"quarryStart") --Allows for startDown variable
  1438.   eventAdd("goto",0,1,1,2, "quarryStart") --Go back to base
  1439.   runAllEvents()
  1440.   --Output to a chest or sit there
  1441.   if enderChestEnabled then
  1442.     if dropSide == "right" then eventAdd("turnTo(1)") end --Turn to proper drop side
  1443.     if dropSide == "left" then eventAdd("turnTo(3)") end
  1444.     eventAdd("dig(false)") --This gets rid of a block in front of the turtle.
  1445.     eventAdd("select",enderChestSlot)
  1446.     eventAdd("turtle.place")
  1447.     eventAdd("select(1)")
  1448.   end
  1449.   eventAdd("drop",dropSide, true)
  1450.   eventAdd("turnTo(0)")
  1451.  
  1452.   --Display was moved above to be used in bedrock function
  1453.   eventAdd("display")
  1454.   --Log current mining run
  1455.   eventAdd("logMiningRun",logExtension)
  1456.   toQuit = true --I'll use this flag to clean up
  1457.   runAllEvents()
  1458.   --Cleanup
  1459.   turtle.getFuelLevel = getFuel
  1460. end
  1461. function bedrock()
  1462.   foundBedrock = true --Let everyone know
  1463.   if rednetEnabled then biometrics() end
  1464.   if checkFuel() == 0 then error("No Fuel",0) end
  1465.   local origin = {x = xPos, y = yPos, z = zPos}
  1466.   print("Bedrock Detected")
  1467.   if turtle.detectUp() then
  1468.     print("Block Above")
  1469.     local var
  1470.     if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end
  1471.     goto(xPos,zPos,yPos,var)
  1472.     for i=1, relxPos do mine(false, false); end
  1473.   end
  1474.   eventClear() --Get rid of any excess events that may be run. Don't want that.
  1475.   endingProcedure()
  1476.   print("\nFound bedrock at these coordinates: ")
  1477.   print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  1478.   error("",0)
  1479. end
  1480.  
  1481. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  1482. local halfFacing = 1
  1483. local toFace = coterminal(wasFacing + 2) --Opposite side
  1484. if zPos == startZ then
  1485.   if facing ~= halfFacing then turnTo(halfFacing) end
  1486.   mine(unpack(mineFunctionTable or {}))
  1487. end
  1488. if facing ~= toFace then
  1489.   turnTo(toFace)
  1490. end
  1491. end
  1492.  
  1493.  
  1494. -------------------------------------------------------------------------------------
  1495. --Pre-Mining Stuff dealing with session persistence
  1496. runAllEvents()
  1497. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  1498.  
  1499. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  1500. if not restoreFoundSwitch then --Regularly
  1501.   --Check if it is a mining turtle
  1502.   if not isMiningTurtle then
  1503.     local a, b = turtle.dig()
  1504.     if a then mined = mined + 1; isMiningTurtle = true
  1505.     elseif b == "Nothing to dig with" then
  1506.       print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  1507.       error("",0)
  1508.     end
  1509.   end
  1510.   mine(false,false,true) --Get into quarry by going forward one
  1511.   if gpsEnabled and not restoreFoundSwitch then --The initial locate is done in the arguments. This is so I can figure out what quadrant the turtle is in.
  1512.     gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  1513.   end
  1514.   for i = 1, startDown do
  1515.     eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  1516.   end
  1517.   runAllEvents()
  1518.   if not(y == 1 or y == 2) then down() end --Go down. If y is one or two, it doesn't need to do this.
  1519. else --restore found
  1520.   if not(layersDone == layers and not doDigDown) then digDown() end
  1521.   if not(layersDone == layers and not doDigUp) then digUp() end  --Get blocks missed before stopped
  1522. end
  1523. --Mining Loops--------------------------------------------------------------------------
  1524. select(1)
  1525. while layersDone <= layers do -------------Height---------
  1526. local lastLayer = layersDone == layers --If this is the last layer
  1527. local secondToLastLayer = (layersDone + 1) == layers --This is for the going down at the end of a layer.
  1528. moved = moved + 1 --To account for the first position in row as "moved"
  1529. if not(layersDone == layers and not doDigDown) then digDown() end --This is because it doesn't mine first block in layer
  1530. if not restoreFoundSwitch then rowCheck = true end
  1531. relxCalc()
  1532. while zPos <= z do -------------Width----------
  1533. while relxPos < x do ------------Length---------
  1534. mine(not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)) --This will be the idiom that I use for the mine function
  1535. end ---------------Length End-------
  1536. if zPos ~= z then --If not on last row of section
  1537.   local func
  1538.   if rowCheck == true then --Swithcing to next row
  1539.   func = "right"; rowCheck = false; else func = false; rowCheck = true end --Which way to turn
  1540.     eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  1541.     runAllEvents()
  1542. else break
  1543. end
  1544. end ---------------Width End--------
  1545. eventAdd("goto",1,1,yPos,0, "layerStart") --Goto start of layer
  1546. if not lastLayer then --If there is another layer
  1547.   for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do eventAdd("down()") end --The fromBoolean stuff means that if lastheight is 1 and last and layer, will only go down two
  1548. end
  1549. eventAdd("setRowCheckFromPos")
  1550. eventAdd("relxCalc")
  1551. layersDone = layersDone + 1
  1552. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  1553. runAllEvents()
  1554. end ---------------Height End-------
  1555.  
  1556. endingProcedure() --This takes care of getting to start, dropping in chest, and displaying ending screen
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top