Advertisement
civilwargeeky

Quarry 3.6.0

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