civilwargeeky

Quarry 3.3.0

Nov 23rd, 2013
806
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[
  2. Version 3.3.0
  3. Recent Changes:
  4.   New Internals: Made event system and consolidated mining loops
  5.   New Restarting Logic!
  6.     As long as position is recorded properly, it should always restart properly
  7.   New Argument logic!
  8.     Arguments are much more modular for me to make, and they are no longer case-sensitive. Improved items changed interface
  9.   New Arguments!
  10.     -enderChest [t/f or slot number] You can now use an enderchest! Try it out. There are directions
  11.     -startDown [number] The quarry will now start this many blocks down from its starting point (or up if invert). Great for getting diamonds and things from surface. Chest should still be placed on the top (or use ender chest)
  12.     -manualPos [xPos] [zPos] [yPos] [facing] Turtle ever gotten it's position wrong, but you don't want to reset? Use this! Check "quarry -help" for changes
  13.   Renamed several arguments
  14.   Arguments are no longer ignored if you use "-default", you just won't be prompted for anything.
  15.   Boolean (t/f) arguments now accept "yes" as well as "true"
  16.   Fixed small issue in GPS location that may have broken it.
  17. ]]
  18. --Defining things
  19. _G.civilTable = {}; civilTable = nil; setmetatable(civilTable, {__index = _G}); setfenv(1,civilTable)
  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 = 10 --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. numberOfStacksPerRun = 8 --How many stacks (number of items) the turtle expects (on average) to have before it must dump off. Not in arguments. [Default 8]
  36. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  37. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  38. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  39. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  40. logExtension = "" --The extension of the file (e.g. ".txt") [Default ""]
  41. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  42. enderChestEnabled = false --Whether or not to use an ender chest [Default false]
  43. enderChestSlot = 16 --What slot to put the ender chest in [Default 16]
  44. --Standard number slots for fuel (you shouldn't care)
  45. fuelTable = { --Will add in this amount of fuel to requirement.
  46. safe = 1000,
  47. moderate = 200,
  48. loose = 0 } --Default 1000, 200, 0
  49. --Standard rednet channels
  50. channels = {
  51. send = os.getComputerID()  ,
  52. receive = os.getComputerID() + 100 ,
  53. confirm = "Confirm"
  54. }
  55.  
  56. local help_paragraph = [[
  57. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  58. -Default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  59. -dim: [length] [width] [height] This sets the dimensions for the quarry
  60. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  61. -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
  62. -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
  63. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  64. -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...
  65. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  66. -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.
  67. -GPS: [t/f] If true 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
  68. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  69. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  70. -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
  71. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  72. -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...)
  73. -saveFile: [word] This is what the backup file will be called
  74. -logFolder: [word] The folder that quarry logs will be stored in
  75. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  76. -invCheckFreq: [number] This is how often the turtle will check if it has the proper amount of slots open
  77. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every invCheckFreq blocks
  78. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  79. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  80.   =
  81.   C _ |
  82.       |
  83.       |
  84.       |
  85.       |_ _ _ _ >
  86. -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"
  87. -help: Thats what this is :D
  88. Examples: Everything below is examples and tips for use
  89. Important Note:
  90.  None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  91. Examples [1]:
  92.  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".
  93.   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?
  94. Examples [2]:
  95.   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.
  96. Examples [2] [cont.]:
  97.   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
  98.   "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  99.   BAM. Now you can just let that turtle do it's thing
  100. Tips:
  101.  The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  102.  
  103.   Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  104. Tips [cont.]:
  105.  For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  106.  
  107.  For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  108. Tips [cont.]:
  109.  If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  110.  
  111.   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.
  112. Internal Config:
  113.   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.
  114.  
  115.   You can also use this if there are settings that you don't like the default value of.
  116. ]]
  117.  
  118. --Parsing help for display
  119. --[[The way the help table works:
  120. All help indexes are numbered. There is a help[i].title that contains the title,
  121. and the other lines are in help[i][1] - help[i][#help[i] ]
  122. Different lines (e.g. other than first) start with a space.
  123. As of now, the words are not wrapped, fix that later]]
  124. local help = {}
  125. local i = 0
  126. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  127. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  128. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  129. local current = string.sub(a,1,-2).."" --Concatenate Trick
  130. if string.sub(current,1,1) ~= " " then
  131. i = i + 1
  132. help[i] = {}
  133. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  134. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  135. elseif string.sub(current,1,1) == " " then
  136. table.insert(help[i], string.sub(current,2, -1).."")
  137. end
  138. end
  139.  
  140.  
  141. local supportsRednet = (peripheral.wrap("right") ~= nil)
  142.  
  143. local tArgs = {...}
  144. --You don't care about these
  145.       xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, startY
  146.     = 0,   1,   1,   0,     0,      0,    0,    1,       "right",  false,     true,     1,          0,        0
  147.  
  148. local totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function)
  149. local function count() --Done any time inventory dropped and at end
  150. slot = {}        --1: Cobble 2: Fuel 3:Other
  151. for i=1, 16 do   --[1] is type, [2] is number
  152. slot[i] = {}
  153. slot[i][2] = turtle.getItemCount(i)
  154. end
  155. slot[1][1] = 1   -- = Assumes Cobble/Main
  156. for i=1, 16 do   --Cobble Check
  157. turtle.select(i)
  158. if turtle.compareTo(1)  then
  159. slot[i][1] = 1
  160. totals.cobble = totals.cobble + slot[i][2]
  161. elseif turtle.refuel(0) then
  162. slot[i][1] = 2
  163. totals.fuel = totals.fuel + slot[i][2]
  164. else
  165. slot[i][1] = 3
  166. totals.other = totals.other + slot[i][2]
  167. end
  168. end
  169. turtle.select(1)
  170. end
  171.  
  172. local getFuel = turtle.getFuelLevel --This is for cleanup at the end
  173. do --Common variable name...
  174. local flag = turtle.getFuelLevel() == "unlimited"--Unlimited screws up my calculations
  175. if flag then --Fuel is disabled
  176.   turtle.getFuelLevel = function() return math.huge end --Infinite Fuel
  177. end --There is no "else" because it will already return the regular getFuel
  178. end
  179. local checkFuel = turtle.getFuelLevel --Just an alias for backwards compat
  180.  
  181.  -----------------------------------------------------------------
  182. --Input Phase
  183. local function screen(xPos,yPos)
  184. xPos, yPos = xPos or 1, yPos or 1
  185. term.setCursorPos(xPos,yPos); term.clear(); end
  186. local function screenLine(xPos,yPos)
  187. term.setCursorPos(xPos,yPos); term.clearLine(); end
  188.  
  189. screen(1,1)
  190. print("----- Welcome to Quarry! -----")
  191. print("")
  192.  
  193. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  194. local changedT, tArgsWithUpper = {}, {}
  195. changedT.new = function(key, value) table.insert(changedT,{key, value}) end --Numeric list of lists
  196. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  197. 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
  198.  
  199. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  200. 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.
  201.   if trigger == nil then trigger = true end --Defaults to being able to run
  202.   if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  203.   if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these
  204.   local toGetText = name:lower() --Because all params are now lowered
  205.   local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  206.   local args = formatString:sub(({formatString:find(formatType)})[2] + 2).."" --Everything in formatString but the type and space
  207.   local variable = variableOverride or name --Goes first to the override for name
  208.   local func = loadstring("return "..variable)
  209.   setfenv(func,getfenv(1))
  210.   local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  211.   if originalValue == nil then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  212.   local givenValue, toRet --Initializing for use
  213.   if tArgs["-"..toGetText] then
  214.     givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  215.   elseif forcePrompt then
  216.     term.write(displayText.."? ")
  217.     givenValue = io.read()
  218.   end
  219.   if not givenValue then return end --Don't do anything if you aren't given anything. Leave it as default
  220.   if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  221.     toRet = givenValue:sub(1,1):lower() == "y" or givenValue:sub(1,1):lower() == "t" --Accepts true or yes
  222.     if formatString == "boolean special" then
  223.       toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  224.     end
  225.   elseif formatType == "string" then
  226.     toRet = givenValue:match("^[%w%.]+") --Basically anything not a space or control character etc
  227.   elseif formatType == "number" then
  228.     toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  229.     if not toRet then return end --We need a number... Otherwise compare errors
  230.     toRet = math.abs(math.floor(toRet)) --Get proper integers
  231.     local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  232.     startNum, endNum = tonumber(startNum), tonumber(endNum)
  233.     if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  234.   elseif formatType == "side" then
  235.     local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  236.     for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  237.     if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  238.   elseif formatType == "list" then
  239.     toRet = {}
  240.     for a in args:gmatch("[^,]") do
  241.       table.insert(toRet,a)
  242.     end
  243.   else error("Improper formatType",2)
  244.   end
  245.   if toRet == nil then return end --Don't want to set variables to nil... That's bad
  246.   tempParam = toRet --This is what loadstring will see :D
  247.   local func = loadstring(variable.." = tempParam")
  248.   setfenv(func, getfenv(1))
  249.   func()
  250.   tempParam = nil --Cleanup of global
  251.   if toRet ~= originalValue then
  252.     changedT.new(displayText, tostring(toRet))
  253.   end
  254.   return toRet
  255. end
  256.  
  257. --Check if it is a turtle
  258. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then
  259.   print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  260.   print("Press 'q' to quit, or any other key to start help ")
  261.   if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  262. end
  263.  
  264.  
  265. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  266. print("You have selected help, press any key to continue"); print("Use arrow keys to naviate, q to quit"); os.pullEvent("key")
  267. local pos = 1
  268. local key = 0
  269. while pos <= #help and key ~= keys.q do
  270. if pos < 1 then pos = 1 end
  271. screen(1,1)
  272. print(help[pos].title)
  273. for a=1, #help[pos] do print(help[pos][a]) end
  274. repeat
  275. _, key = os.pullEvent("key")
  276. until key == 200 or key == 208 or key == keys.q
  277. if key == 200 then pos = pos - 1 end
  278. if key == 208 then pos = pos + 1 end
  279. end
  280. error("",0)
  281. end
  282.  
  283. --Saving
  284. addParam("doBackup", "Backup Save File", "boolean")
  285. addParam("saveFile", "Save File Name", "string")
  286.  
  287. restoreFound = fs.exists(saveFile)
  288. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"]) and restoreFound
  289. if restoreFoundSwitch then
  290.   local file = fs.open(saveFile,"r")
  291.   local test = file.readAll() ~= ""
  292.   file.close()
  293.   if test then
  294.     os.run(getfenv(1),saveFile)
  295.     if gpsEnabled then --If it had saved gps coordinates
  296.       print("Found GPS Start Coordinates")
  297.       local currLoc = {gps.locate(gpsTimeout)} or {}
  298.       if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  299.         print("GPS Position Successfully Read")
  300.         if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  301.           xPos, yPos, zPos = 0,1,1
  302.           if facing ~= 0 then turnTo(0) end
  303.           print("Is at start")
  304.         else
  305.           if inverted then --yPos setting
  306.           ------------------------------------------------FIX THIS
  307.           end
  308.           local function copyTable(tab) local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end
  309.           local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  310.           if b[3] - a[3] == -1 then--If went north (-Z)
  311.             a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  312.             xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  313.           elseif b[1] - a[1] == 1 then--If went east (+X)
  314.             a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  315.             xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  316.           elseif b[3] - a[3] == 1 then--If went south (+Z)
  317.             a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  318.             xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  319.           elseif b[1] - a[1] == -1 then--If went west (-X)
  320.             a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  321.             xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  322.           else
  323.             print("Improper Coordinates")
  324.             print("GPS Locate Failed, Using Standard Methods")        ----Maybe clean this up a bit to use flags instead.
  325.           end  
  326.         end
  327.         print("X Pos: ",xPos)
  328.         print("Y Pos: ",yPos)
  329.         print("Z Pos: ",zPos)
  330.         print("Facing: ",facing)
  331.       else
  332.         print("GPS Locate Failed, Using Standard Methods")
  333.       end    
  334.     print("Restore File read successfully. Starting in 3"); sleep(3)
  335.     end
  336.   else
  337.     fs.delete(saveFile)
  338.     print("Restore file was empty, sorry, aborting")
  339.     error("",0)
  340.   end
  341. else --If turtle is just starting
  342.   events = {} --This is the event queue :D
  343.   originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  344. end
  345.  
  346. --Dimesnions
  347. if tArgs["-dim"] then local num = tArgs["-dim"];
  348. x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  349. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  350. print("What dimensions?")
  351. print("")
  352. --This will protect from negatives, letters, and decimals
  353. term.write("Length? ")
  354. x = math.floor(math.abs(tonumber(io.read()) or x))
  355. term.write("Width? ")
  356. z = math.floor(math.abs(tonumber(io.read()) or z))
  357. term.write("Height? ")
  358. y = math.floor(math.abs(tonumber(io.read()) or y))
  359. changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  360. end
  361. --Invert
  362. addParam("invert", "Inverted","boolean", true, nil, "inverted")
  363. addParam("startDown","Start Down","number 1-256")
  364. --Inventory
  365. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  366. addParam("enderChest","Ender Chest Enabled","boolean special", nil, nil, "enderChestEnabled") --This will accept anything (including numbers) thats not "f" or "n"
  367. addParam("enderChest", "Ender Chest Slot", "number 1-16", nil, nil, "enderChestSlot") --This will get the number slot if given
  368. --Rednet
  369. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet)
  370. addParam("gps", "GPS Location Services", "boolean", nil, (not restoreFoundSwitch) and supportsRednet, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  371. if gpsEnabled then
  372.   gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  373.   gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  374. end
  375. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  376. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  377. --Fuel
  378. addParam("doRefuel", "Refuel from Inventory","boolean", nil, turtle.getFuelLevel() ~= math.huge) --math.huge due to my changes
  379. addParam("doCheckFuel", "Check Fuel", "boolean", nil, turtle.getFuelLevel() ~= math.huge)
  380. --Logging
  381. addParam("logging", "Logging", "boolean")
  382. addParam("logFolder", "Log Folder", "string")
  383. addParam("logExtension","Log Extension", "string")
  384. --Misc
  385. addParam("startY", "Start Y","number 1-256")
  386. addParam("invCheckFreq","Inventory Check Frequency","number 1-342")
  387. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  388. addParam("careAboutResources", "Care About Resources","boolean")
  389. --Manual Position
  390. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  391.   local a = tArgs["-manualpos"]
  392.   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
  393.   changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  394.   restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  395. end
  396.  
  397. local function saveProgress(extras) --Session persistence
  398. exclusions = { modem = true, }
  399. if doBackup then
  400. local toWrite = ""
  401. for a,b in pairs(getfenv(1)) do
  402.   if not exclusions[a] then
  403.       --print(a ,"   ", b, "   ", type(b)) --Debug
  404.     if type(b) == "string" then b = "\""..b.."\"" end
  405.     if type(b) == "table" then b = textutils.serialize(b) end
  406.     if type(b) ~= "function" then
  407.       toWrite = toWrite..a.." = "..tostring(b).."\n"
  408.     end
  409.   end
  410. end
  411. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnesesary
  412. local file
  413. repeat
  414.   file = fs.open(saveFile,"w")
  415. until file --WHY DOES IT SAY ATTEMPT TO INDEX NIL!!!
  416. file.write(toWrite)
  417. if type(extras) == "table" then
  418.   for a, b in pairs(extras) do
  419.     file.write(a.." = "..tostring(b))
  420.   end
  421. end
  422. file.close()
  423. end
  424. end
  425.  
  426. local area = x*z
  427. local volume = x*y*z
  428. local lastHeight = y%3
  429. layers = math.ceil(y/3)
  430. local yMult = layers --This is basically a smart y/3 for movement
  431. local moveVolume = (area * yMult) --Kept for display percent
  432. --Calculating Needed Fuel--
  433. local exStack = numberOfStacksPerRun --Expected stacks of items before full
  434. neededFuel = yMult * x * z + --This is volume it will run through
  435.       (startDown + y)*(2+1/(64*exStack)) + --This is simplified and includes the y to get up times up and down + how many times it will drop stuff off
  436.       (x+z)*(yMult + 1/(64*exStack))  --Simplified as well: It is getting to start of row plus getting to start of row how many times will drop off stuff
  437.       --Original equation: x*z*y/3 + y * 2 + (x+z) * y/3 + (x + z + y) * (1/64*8)
  438. neededFuel = math.ceil(neededFuel)
  439.  
  440. --Getting Fuel
  441. if doCheckFuel and checkFuel() < neededFuel then
  442. neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  443.   print("Not enough fuel")
  444.   print("Current: ",checkFuel()," Needed: ",neededFuel)
  445.   print("Starting SmartFuel...")
  446.   sleep(2) --So they can read everything.
  447.   term.clear()
  448.   local oneFuel, neededFuelItems
  449.   local currSlot = 0
  450.   local function output(text, x, y) --For displaying fuel
  451.     currX, currY = term.getCursorPos()
  452.     term.setCursorPos(x,y)
  453.     term.clearLine()
  454.     term.write(text)
  455.     term.setCursorPos(currX,currY)
  456.     end
  457.   local function roundTo(num, target) --For stacks of fuel
  458.     if num >= target then return target elseif num < 0 then return 0 else return num end
  459.   end
  460.   local function updateScreen()
  461.     output("Welcome to SmartFuel! Now Refueling...", 1,1)
  462.     output("Currently taking fuel from slot "..currSlot,1,2)
  463.     output("Current single fuel: "..tostring(oneFuel or 0),1,3)
  464.     output("Current estimate of needed fuel: ",1,4)
  465.     output("Single Items: "..math.ceil(neededFuelItems or 0),4,5)
  466.     output("Stacks:       "..math.ceil((neededFuelItems or 0) / 64),4,6)
  467.     output("Needed Fuel: "..tostring(neededFuel),1,12)
  468.     output("Current Fuel: "..tostring(checkFuel()),1,13)
  469.   end
  470.   while checkFuel() <= neededFuel do
  471.     currSlot = currSlot + 1
  472.     turtle.select(currSlot)
  473.     updateScreen()
  474.     while turtle.getItemCount(currSlot) == 0 do sleep(1.5) end
  475.     repeat
  476.       local previous = checkFuel()
  477.       turtle.refuel(1)
  478.       oneFuel = checkFuel() - previous
  479.       updateScreen()
  480.     until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  481.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  482.     turtle.refuel(math.ceil(roundTo(neededFuelItems, 64))) --Change because can only think about 64 at once.
  483.     if turtle.getItemCount(roundTo(currSlot + 1, 16)) == 0 then --Resets if no more fuel
  484.       currSlot = 0
  485.     end
  486.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  487.   end
  488. end
  489. --Ender Chest Obtaining
  490. if enderChestEnabled then
  491.   while turtle.getItemCount(enderChestSlot) ~= 1 do
  492.     screen(1,1)
  493.     print("You have decided to use an Ender Chest!")
  494.     print("Please place one Ender Chest in slot ",enderChestSlot)
  495.     sleep(1)
  496.   end
  497.   print("Ender Chest in slot ",enderChestSlot, " checks out")
  498.   sleep(2)
  499. end
  500. --Initial Rednet Handshake
  501. if rednetEnabled then
  502. screen(1,1)
  503. print("Rednet is Enabled")
  504. print("The Channel to open is "..channels.send)
  505. modem = peripheral.wrap("right")
  506. modem.open(channels.receive)
  507. local i = 0
  508. repeat
  509. local id = os.startTimer(3)
  510. i=i+1
  511. print("Sending Initial Message "..i)
  512. modem.transmit(channels.send, channels.receive, "{ 'Initial' }")
  513. local message
  514. repeat
  515. local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  516. message = locMessage
  517. until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and message == channels.confirm)
  518. until message == channels.confirm
  519. connected = true
  520. print("Connection Confirmed!")
  521. sleep(1.5)
  522. end
  523. local function biometrics(sendChannel)
  524. local commands = { Confirm = "Confirm" }
  525. local toSend = { ["x"] = x, ["y"] = (layers), ["z"] = z, --The y calc is weird...
  526.     ["xPos"] = xPos, ["yPos"] = yPos, ["zPos"] = zPos,
  527.     ["percent"] = percent, ["mined" ]= mined,
  528.     ["fuel"] = checkFuel(), ["moved"] = moved,
  529.     ["remainingBlocks"] = (volume-mined), ["ID"] = os.getComputerID(),
  530.     ["isInPath"] = isInPath, --Whether it is going back to start
  531.     ["volume"] = volume, ["area"] = area}
  532. modem.transmit(channels.send, channels.receive, textutils.serialize(toSend))
  533. id = os.startTimer(0.1)
  534. local event, message
  535. repeat
  536. local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  537. event, message = locEvent, locMessage
  538. until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive)
  539. if event == "modem_message" then connected = true else connected = false end
  540. --Stuff to do for different commands
  541. end
  542. --Showing changes to settings
  543. screen(1,1)
  544. print("Your selected settings:")
  545. if #changedT == 0 then
  546. print("Completely Default")
  547. else
  548. for i=1, #changedT do
  549. print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  550. end
  551. end
  552. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  553.  
  554.  
  555.  
  556. ----------------------------------------------------------------
  557. --Define ALL THE FUNCTIONS
  558. function eventAdd(...)
  559.   return table.insert(events,1, {...}) or true
  560. end
  561. function eventGet(pos)
  562.   return events[tonumber(pos) or #events]
  563. end
  564. function eventPop(pos)
  565.   return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  566. end
  567. function eventRun(value, ...)
  568.   local argsList = {...}
  569.   if type(value) == "string" then
  570.     if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  571.       value = value .. "("
  572.       for a, b in pairs(argsList) do --Appending arguments
  573.         local toAppend
  574.         if type(b) == "table" then toAppend = textutils.serialize(b)
  575.         elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  576.         else toAppend = tostring(b) end
  577.         value = value .. (toAppend or "true") .. ", "
  578.       end
  579.       if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  580.         value = value:sub(1,-3)..""
  581.       end
  582.       value = value .. ")"
  583.     end
  584.     --print(value) --Debug
  585.     local func = loadstring(value)
  586.     setfenv(func, getfenv(1))
  587.     return func()
  588.   end
  589. end
  590.      
  591. function runAllEvents()
  592.   while #events > 0 do
  593.     local toRun = eventGet()
  594.     --print(toRun[1]) --Debug
  595.     eventRun(unpack(toRun))
  596.     eventPop()
  597.   end
  598. end
  599.  
  600. function display() --This is just the last screen that displays at the end
  601. screen(1,1)
  602. print("Total Blocks Mined: "..mined)
  603. print("Current Fuel Level: "..turtle.getFuelLevel())
  604. print("Cobble: "..totals.cobble)
  605. print("Usable Fuel: "..totals.fuel)
  606. print("Other: "..totals.other)
  607. if rednetEnabled then
  608. print("")
  609. print("Sent Stop Message")
  610. finalTable = {{["Mined: "] = mined}, {["Cobble: "] = totals.cobble}, {["Fuel: "] = totals.fuel},
  611.     {["Other: "] = totals.other}, {["Fuel: "] = checkFuel()} }
  612. modem.transmit(channels.send,channels.receive,"stop")
  613. modem.transmit(channels.send,channels.receive,textutils.serialize(finalTable))
  614. modem.close(channels.receive)
  615. end
  616. if doBackup then fs.delete(saveFile) end
  617. end
  618. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  619. screen(1,1)
  620. print("Blocks Mined")
  621. print(mined)
  622. print("Percent Complete")
  623. print(percent.."%")
  624. print("Fuel")
  625. print(checkFuel())
  626.   -- screen(1,1)
  627.   -- print("Xpos: ")
  628.   -- print(xPos)
  629.   -- print("RelXPos: ")
  630.   -- print(relxPos)
  631.   -- print("Z Pos: ")
  632.   -- print(zPos)
  633.   -- print("Y pos: ")
  634.   -- print(yPos)
  635. if rednetEnabled then
  636. screenLine(1,7)
  637. print("Connected: "..tostring(connected))
  638. end
  639. end
  640. function logMiningRun(textExtension, extras) --Logging mining runs
  641. if logging then
  642. local number
  643. if not fs.isDir(logFolder) then
  644.   fs.delete(logFolder)
  645.   fs.makeDir(logFolder)
  646.   number = 1
  647. else
  648.   local i = 0
  649.   repeat
  650.     i = i + 1
  651.   until not fs.exists(logFolder.."/Quarry_Log_"..tostring(i)..(textExtension or ""))
  652.   number = i
  653. end
  654. handle = fs.open(logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or ""),"w")
  655. local function write(...)
  656.   for a, b in ipairs({...}) do
  657.     handle.write(tostring(b))
  658.   end
  659.   handle.write("\n")
  660. end
  661. write("Welcome to the Quarry Logs!")
  662. write("Entry Number: ",number)
  663. write("Dimensions (X Z Y): ",x," ",z," ", y)
  664. write("Blocks Mined: ", mined)
  665. write("  Cobble: ", totals.cobble)
  666. write("  Usable Fuel: ", totals.fuel)
  667. write("  Other: ",totals.other)
  668. write("Total Fuel Used: ",  (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  669. write("Expected Fuel Use: ", neededFuel)
  670. handle.close()
  671. end
  672. end
  673. function isFull(slots)
  674.   slots = slots or 16
  675.   local numUsed = 0
  676.   sleep(0)
  677.   for i=1, 16 do
  678.     if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  679.   end
  680.   if numUsed > slots then
  681.     return true
  682.   end
  683.   return false
  684. end
  685. function dig(doAdd, func)
  686.   doAdd = doAdd or true
  687.   func = func or turtle.dig
  688.   if func() then
  689.     if doAdd then
  690.       mined = mined + 1
  691.     end
  692.     return true
  693.   end
  694.   return false
  695. end
  696. function digUp(doAdd)
  697.     return dig(doAdd,turtle.digUp)
  698. end
  699. function digDown(doAdd)
  700.     return dig(doAdd,turtle.digDown)
  701. end
  702. function relativeXCalc()
  703.   if rowCheck == "right" then relxPos = xPos else relxPos = (x-xPos)+1 end
  704. end
  705. function forward(doAdd)
  706.   if doAdd == nil then doAdd = true end
  707.   if turtle.forward() then
  708.     if doAdd then
  709.       moved = moved + 1
  710.     end
  711.     if facing == 0 then
  712.       xPos = xPos + 1
  713.     elseif facing == 1 then
  714.       zPos = zPos + 1
  715.     elseif facing == 2 then
  716.       xPos = xPos - 1
  717.     elseif facing == 3 then
  718.       zPos = zPos - 1
  719.     else
  720.       error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  721.     end
  722.     relativeXCalc()
  723.     return true
  724.   end
  725.   return false
  726. end
  727. function up(sneak)
  728.   sneak = sneak or 1
  729.   if inverted and sneak == 1 then
  730.     down(-1)
  731.   else
  732.     while not turtle.up() do
  733.       if not digUp() then
  734.         attackUp()
  735.         sleep(0.5)
  736.       end
  737.     end
  738.     yPos = yPos - sneak --Oh! I feel so clever
  739.   end                   --This works because inverted :)
  740.   saveProgress()
  741. end
  742. function down(sneak)
  743.   sneak = sneak or 1
  744.   local count = 0
  745.   if inverted and sneak == 1 then
  746.     up(-1)
  747.   else
  748.     while not turtle.down() do
  749.       count = count + 1
  750.       if not digDown() then
  751.         attackDown()
  752.         sleep(0.2)
  753.       end
  754.       if count > 20 then bedrock() end
  755.     end
  756.     yPos = yPos + sneak
  757.   end
  758.   saveProgress()
  759. end
  760. function right(num)
  761.   num = num or 1
  762.   for i=1, num do facing = coterminal(facing+1); saveProgress(); turtle.turnRight() end
  763. end
  764. function left(num)
  765.   num = num or 1
  766.   for i=1, num do facing = coterminal(facing-1); saveProgress(); turtle.turnLeft() end
  767. end
  768. function attack(doAdd, func)
  769.   doAdd = doAdd or true
  770.   func = func or turtle.attack
  771.   if func() then
  772.     if doAdd then
  773.       attacked = attacked + 1
  774.     end
  775.     return true
  776.   end
  777.   return false
  778. end
  779. function attackUp(doAdd)
  780.   if inverted then
  781.     return attack(doAdd, turtle.attackDown)
  782.   else
  783.     return attack(doAdd, turtle.attackUp)
  784.   end
  785. end
  786. function attackDown(doAdd)
  787.   if inverted then
  788.     return attack(doAdd, turtle.attackUp)
  789.   else
  790.     return attack(doAdd, turtle.attackDown)
  791.   end
  792. end
  793.  
  794.  
  795. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  796. if doCheckInv == nil then doCheckInv = true end
  797. if doDigDown == nil then doDigDown = true end
  798. if doDigUp == nil then doDigUp = true end
  799. if outOfPath == nil then outOfPath = false end
  800. if inverted then
  801.   doDigUp, doDigDown = doDigDown, doDigUp --Just Switch the two if inverted
  802. end
  803. if doRefuel and checkFuel() <= fuelTable[fuelSafety]/2 then
  804.   for i=1, 16 do
  805.   if turtle.getItemCount(i) > 0 then
  806.     turtle.select(i)
  807.     if checkFuel() < 200 + fuelTable[fuelSafety] then
  808.       turtle.refuel()
  809.     end
  810.   end
  811.   end
  812. end
  813. local count = 0
  814. while not forward(not outOfPath) do
  815.   sleep(0) --Calls coroutine.yield to prevent errors
  816.   count = count + 1
  817.   if not dig() then
  818.     attack()
  819.   end
  820.   if count > 10 then
  821.     attack()
  822.     sleep(0.2)
  823.   end
  824.   if count > 50 then
  825.     if turtle.getFuelLevel() == 0 then --Don't worry about inf fuel because I modified this function
  826.       saveProgress({doCheckFuel = true})
  827.       error("No more fuel",0)
  828.     elseif yPos > (startY-7) then --If it is near bedrock
  829.       bedrock()
  830.     else --Otherwise just sleep for a bit to avoid sheeps
  831.       sleep(1)
  832.     end
  833.   end
  834. end
  835. checkSanity() --Not kidding... This is necessary
  836. saveProgress(tab)
  837. if doDigUp then
  838. while turtle.detectUp() do
  839.   sleep(0) --Calls coroutine.yield
  840.   if not digUp() then
  841.     attackUp()
  842.     count = count + 1
  843.   end
  844.   if count > 50 and yPos > (startY-7) then --Same deal with bedrock as above
  845.     bedrock()
  846.   end
  847.   end
  848. end
  849. if doDigDown then
  850.  digDown()
  851. end
  852. percent = math.ceil(moved/moveVolume*100)
  853. updateDisplay()
  854. isInPath = (not outOfPath) --For rednet
  855. if doCheckInv and careAboutResources then
  856. if moved%invCheckFreq == 0 then
  857.  if isFull(16-keepOpen) then dropOff() end
  858. end; end
  859. if rednetEnabled then biometrics() end
  860. end
  861. --Insanity Checking
  862. function checkSanity()
  863.   if isInPath and not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  864.     turnTo(0)
  865.     rowCheck = "right"
  866.   end
  867.   if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  868.     saveProgress()
  869.     print("Oops. Detected that quarry was outside of predefined boundaries.")
  870.     print("Please go to my forum thread and report this with a short description of what happened")
  871.     print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  872.     error("",0)
  873.   end
  874. end
  875.  
  876. local function fromBoolean(input) --Like a calculator
  877. if input then return 1 end
  878. return 0
  879. end
  880. local function multBoolean(first,second) --Boolean multiplication
  881. return (fromBoolean(first) * fromBoolean(second)) == 1
  882. end
  883. function coterminal(num, limit) --I knew this would come in handy :D
  884. limit = limit or 4 --This is for facing
  885. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  886. end
  887. if tArgs["-manualpos"] then
  888.   facing = coterminal(facing) --Done to improve support for "-manualPos"
  889.   if facing == 0 then rowCheck = "right" elseif facing == 2 then rowCheck = "left" end --Ditto
  890.   relativeXCalc() --Ditto
  891. end
  892.  
  893. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  894.  
  895. function turnTo(num)
  896.   num = num or facing
  897.   num = coterminal(num) --Prevent errors
  898.   local turnRight = true
  899.   if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  900.   while facing ~= num do          --The above is used to smartly turn
  901.     if turnRight then
  902.       right()
  903.     else
  904.       left()
  905.     end
  906.   end
  907. end
  908. function goto(x,z,y, toFace)
  909. --Will first go to desired z pos, then x pos, y pos varies
  910. x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  911. if yPos > y then --Will go up first if below position
  912.   while yPos~=y do up() end
  913. end
  914. if zPos > z then
  915.   turnTo(3)
  916. elseif zPos < z then
  917.   turnTo(1)
  918. end
  919. while zPos ~= z do mine(false,false,true,false) end
  920. if xPos > x then
  921.   turnTo(2)
  922. elseif xPos < x then
  923.   turnTo(0)
  924. end
  925. while xPos ~= x do mine(false,false,true,false) end
  926. if yPos < y then --Will go down after if above position
  927.   while yPos~=y do down() end
  928. end
  929. turnTo(toFace,"right")
  930. saveProgress()
  931. end
  932. function drop(side, final, allowSkip)
  933. side = sides[side] or "front"    --The final number means that it will
  934. if final then final = 0 else final = 1 end --drop a whole stack at the end
  935. local allowSkip = allowSkip or (final == 0) --This will allow drop(side,t/f, rednetConnected)
  936. count()
  937. if doRefuel then
  938.   for i=1, 16 do
  939.     if slot[i][1] == 2 then
  940.       turtle.select(i); turtle.refuel()
  941.     end
  942.   end
  943.   turtle.select(1)
  944. end
  945. if side == "right" then turnTo(1) end
  946. if side == "left" then turnTo(3) end
  947. local whereDetect, whereDrop1, whereDropAll
  948. local _1 = slot[1][2] - final --All but one if final, all if not final
  949. if side == "top" then
  950. whereDetect = turtle.detectUp ; whereDrop = turtle.dropUp
  951. elseif side == "bottom" then
  952. whereDetect = turtle.detectDown ; whereDrop = turtle.dropDown
  953. else
  954. whereDetect = turtle.detect; whereDrop = turtle.drop
  955. end
  956. local function waitDrop(val) --This will just drop, but wait if it can't
  957.   val = val or 64
  958.   local try = 1
  959.   while not whereDrop(val) do
  960.     print("Chest Full, Try "..try)
  961.     try = try + 1
  962.     sleep(2)
  963.   end
  964. end
  965. repeat
  966. local detected = whereDetect()
  967. if detected then
  968.   waitDrop(_1)
  969.   for i=1, 2 do --This is so I quit flipping missing items when chests are partially filled
  970.     for i=2, 16 do
  971.       if turtle.getItemCount(i) > 0 then
  972.         turtle.select(i)
  973.         waitDrop(nil, i)
  974.       end
  975.     end
  976.   end
  977. elseif not allowSkip then
  978.   print("Waiting for chest placement place a chest to continue")
  979.   while not whereDetect() do
  980.     sleep(1)
  981.   end
  982. end
  983. until detected or allowSkip
  984. if not allowSkip then totals.cobble = totals.cobble - 1 end
  985. turtle.select(1)
  986. end
  987. function dropOff() --Not local because called in mine()
  988. local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  989. if careAboutResources and not enderChestEnabled then --Regularly
  990. eventAdd("goto", 1,1,currY,2) --Need this step for "-startDown"
  991. eventAdd("goto(0,1,1,2)")
  992. eventAdd("drop", dropSide,false)
  993. eventAdd("turnTo(0)")
  994. eventAdd("mine",false,false,true,false)
  995. eventAdd("goto(1,1,1, 0)")
  996. eventAdd("goto", 1, 1, currY, 0)
  997. eventAdd("goto", currX,currZ,currY,currFacing)
  998. elseif careAboutResources then --If using an enderChest
  999. eventAdd("turnTo",currFacing-2)
  1000. eventAdd("dig",false)
  1001. eventAdd("turtle.select",enderChestSlot)
  1002. eventAdd("turtle.place")
  1003. eventAdd("drop","front",false)
  1004. eventAdd("turtle.select", enderChestSlot)
  1005. eventAdd("dig",false)
  1006. eventAdd("turnTo",currFacing)
  1007. eventAdd("turtle.select(1)")
  1008. end
  1009. runAllEvents()
  1010. return true
  1011. end
  1012. function bedrock()
  1013. if checkFuel() == 0 then error("No Fuel",0) end
  1014. local origin = {x = xPos, y = yPos, z = zPos}
  1015. print("Bedrock Detected")
  1016. if turtle.detectUp() then
  1017. print("Block Above")
  1018. local var
  1019. if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end
  1020. goto(xPos,zPos,yPos,var)
  1021. for i=1, relxPos do mine(true,true); end
  1022. end
  1023. goto(0,1,1,2)
  1024. drop(dropSide, true)
  1025. turnTo(0)
  1026. display()
  1027. print("\nFound bedrock at these coordinates: ")
  1028. print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  1029. error("",0)
  1030. end
  1031.  
  1032. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  1033. local halfFacing = 1
  1034. local toFace = coterminal(wasFacing + 2) --Opposite side
  1035. if zPos == startZ then
  1036.   if facing ~= halfFacing then turnTo(halfFacing) end
  1037.   mine(unpack(mineFunctionTable or {}))
  1038. end
  1039. if facing ~= toFace then
  1040.   turnTo(toFace)
  1041. end
  1042. end
  1043.  
  1044. -------------------------------------------------------------------------------------
  1045. --Pre-Mining Stuff dealing with session persistence
  1046. runAllEvents()
  1047. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  1048.  
  1049. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  1050. 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.
  1051.   gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  1052. end
  1053. if not restoreFoundSwitch then --Regularly
  1054.   --Check if it is a mining turtle
  1055.   if not isMiningTurtle then
  1056.     local a, b = turtle.dig()
  1057.     if a then mined = mined + 1; isMiningTurtle = true
  1058.     elseif b == "Nothing to dig with" then
  1059.       print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  1060.       error("",0)
  1061.     end
  1062.   end
  1063.   mine(false,false,true) --Get into quarry by going forward one
  1064.   for i = 1, startDown do
  1065.     eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  1066.   end
  1067.   runAllEvents()
  1068.   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.
  1069. else --restore found
  1070.   if doDigDown then digDown() end
  1071.   if doDigUp then digUp() end  --Get blocks missed before stopped
  1072. end
  1073. --Mining Loops--------------------------------------------------------------------------
  1074. turtle.select(1)
  1075. while layersDone <= layers do -------------Height---------
  1076. local lastLayer = layersDone == layers --If this is the last layer
  1077. local secondToLastLayer = (layersDone + 1) == layers --This is for the going down at the end of a layer.
  1078. moved = moved + 1 --To account for the first position in row as "moved"
  1079. if not restoreFoundSwitch then rowCheck = "right" end
  1080. relativeXCalc()
  1081. while zPos <= z do -------------Width----------
  1082. while relxPos < x do ------------Length---------
  1083. 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
  1084. end ---------------Length End-------
  1085. if zPos ~= z then --If not on last row of section
  1086.   local func
  1087.   if rowCheck == "right" then --Swithcing to next row
  1088.   func = "right"; rowCheck = "left"; else func = "left"; rowCheck = "right" end --Which way to turn
  1089.     eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  1090.     runAllEvents()
  1091. else break
  1092. end
  1093. end ---------------Width End--------
  1094. eventAdd("goto",1,1,yPos,0) --Goto start of layer
  1095. runAllEvents()
  1096. if not lastLayer then --If there is another layer
  1097.   for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do down() end --The fromBoolean stuff means that if lastheight is 1 and last and layer, will only go down two
  1098. end
  1099. layersDone = layersDone + 1
  1100. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  1101. end ---------------Height End-------
  1102. if doDigDown then --This is because it doesn't mine first block in layer
  1103.   if inverted then
  1104.     digUp()
  1105.   else
  1106.     digDown()
  1107.   end
  1108. end
  1109. eventAdd("goto",1,1,yPos,2) --Allows for startDown variable
  1110. eventAdd("goto",0,1,1,2)
  1111.  
  1112. --Output to a chest or sit there
  1113. if enderChestEnabled and not turtle.detect() then
  1114.   eventAdd("turtle.select",enderChestSlot)
  1115.   eventAdd("turtle.place")
  1116.   eventAdd("turtle.select(1)")
  1117. end
  1118. eventAdd("drop",dropSide, true)
  1119. eventAdd("turnTo(0)")
  1120.  
  1121. --Display was moved above to be used in bedrock function
  1122. eventAdd("display")
  1123. --Log current mining run
  1124. eventAdd("logMiningRun",logExtension)
  1125. toQuit = true --I'll use this flag to clean up
  1126. runAllEvents()
  1127. --Cleanup
  1128. turtle.getFuelLevel = getFuel
RAW Paste Data