Advertisement
civilwargeeky

Quarry 3.5.5

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